C# WebApi 全局配置模型验证和自定义错误处理。config Filters Add ModelStateValidationFilter/CustomExceptionFilter
public static void Start()
{
logger.Debug("Startup WebAPI...");
SwaggerConfig.Register();
GlobalConfiguration.Configure(WebApiConfig.Register);
。。。
public static class WebApiConfig
{ public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes(); config.Filters.Add(new CustomExceptionFilterAttribute());
config.Filters.Add(new ModelStateValidationFilterAttribute());
}
}
CustomExceptionFilterAttribute :
using System;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using GlobalPaymentsPortalWebApi.Exceptions;
using NLog; namespace TestWebApi.Filters
{
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
readonly ILogger logger = LogManager.GetCurrentClassLogger(); public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
var requestInfo = actionExecutedContext.Request.Method.Method + " " + actionExecutedContext.Request.RequestUri.PathAndQuery;
if (actionExecutedContext.Exception is CustomException customException)
{
var res = new CustomErrorResponse(((CustomException)actionExecutedContext.Exception).Code, ((CustomException)actionExecutedContext.Exception).Error);
HttpResponseMessage httpResponse = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
httpResponse.Content = new ObjectContent<CustomErrorResponse>(res, GlobalConfiguration.Configuration.Formatters.JsonFormatter);
actionExecutedContext.Response = httpResponse; string modelErrors = string.Empty;
if (!actionExecutedContext.ActionContext.ModelState.IsValid)
{
modelErrors = actionExecutedContext.ActionContext.ModelState.SelectMany(state => state.Value.Errors).Aggregate("", (current, error) => current + (error.ErrorMessage + " "));
} if (!string.IsNullOrEmpty(customException.Error))
{
logger.Info("{0}: {1} -> [{2}]: {3}", customException.Code, customException.Error, requestInfo, modelErrors);
}
else
{
logger.Info("{0} -> [{1}]: {2}", customException.Code, requestInfo, modelErrors);
}
}
else if (actionExecutedContext.Exception is NotFoundException notfoundException)
{
actionExecutedContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
logger.Info("NotFound -> [{0}]", requestInfo);
}
else
{
actionExecutedContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
logger.Error(actionExecutedContext.Exception, "{0} -> [{1}]", actionExecutedContext.Exception.Message, requestInfo);
}
}
}
}
ModelStateValidationFilterAttribute :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters; namespace TestWebApi.Filters
{
public class ModelStateValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if(!actionContext.ModelState.IsValid)
{
throw new CustomException(CustomError.BadRequestParameter);
} base.OnActionExecuting(actionContext);
}
}
}
CustomException :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks; namespace TestWebApi.Exceptions
{
public enum CustomError
{
Unknown = 0,
BadRequestParameter,
DuplicatedKey,
LoginFailed,
DuplicatedLoyaltyTier,
DuplicatedKioskType,
CancelFailed,
DeployFailed
} [Serializable]
public class CustomException : Exception
{
public CustomError Code { get; } public string Error { get; } public CustomException(CustomError code, string error = null)
{
Code = code;
Error = error;
} }
}
public class CustomErrorResponse
{
[Required]
public CustomError? Code { get; set; } public string Error { get; set; }
public CustomErrorResponse(CustomError code, string error = null)
{
Code = code;
Error = error;
}
}
C# WebApi 全局配置模型验证和自定义错误处理。config Filters Add ModelStateValidationFilter/CustomExceptionFilter的更多相关文章
- webapi Model Validation 模型验证
通常情况下,对于那些经常为别人提供数据接口的开发人员来说,对于调用方传递过来的参数都会有验证处理.例如: if (string.IsNullOrEmpty(entity.Name)) { //当姓名为 ...
- webapi中的模型验证
mic: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-valida ...
- sencha touch Model validations(模型验证,自定义验证)
model Ext.define('app.model.Register', { extend: 'Ext.data.Model', requires: ['Ext.data.JsonP'], con ...
- 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)
一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...
- 一、WebApi模型验证
一.新建项目 选择空的项目webapi 查看启动端口 创建控制器 添加方法 public class VerifController : ApiController { public IHttpAct ...
- webapi - 模型验证
本次要和大家分享的是webapi的模型验证,讲解的内容可能不单单是做验证,但都是围绕模型来说明的:首先来吐槽下,今天下午老板为自己买了套新办公家具,看起来挺好说明老板有钱,不好的是我们干技术的又成了搬 ...
- ASP.NET Core 6.0 基于模型验证的数据验证
1 前言 在程序中,需要进行数据验证的场景经常存在,且数据验证是有必要的.前端进行数据验证,主要是为了减少服务器请求压力,和提高用户体验:后端进行数据验证,主要是为了保证数据的正确性,保证系统的健壮性 ...
- Web API中的模型验证
一.模型验证的作用 在ASP.NET Web API中,我们可以使用 System.ComponentModel.DataAnnotations 命名空间中的属性为模型上的属性设置验证规则. 一个模型 ...
- webapi中使用token验证(JWT验证)
本文介绍如何在webapi中使用JWT验证 准备 安装JWT安装包 System.IdentityModel.Tokens.Jwt 你的前端api登录请求的方法,参考 axios.get(" ...
- ASP.NET Core 中文文档 第四章 MVC(2.2)模型验证
原文:Model Validation 作者:Rachel Appel 翻译:娄宇(Lyrics) 校对:孟帅洋(书缘) 在这篇文章中: 章节: 介绍模型验证 验证 Attribute 模型状态 处理 ...
随机推荐
- 题解:CF888G Xor-MST
题解:CF888G Xor-MST 题目大意:给定 \(n\) 个点的点权, 任意两点间边权是点权的异或和.求这张完全图的 MST 的权值. 思路: Boruvka + Trie树 + 按位贪心. 关 ...
- virsh的基本使用
virsh基础命令 1.查看运行的虚拟机 virsh list 查看所有的虚拟机(关闭和运行的,不包括摧毁的) virsh list --all 2..启动虚拟机 virsh start 虚拟机名称 ...
- manim边做边学--圆环面
Torus类在制作数学.物理或工程领域的动画时具有广泛的应用场景. 比如,通过动态演示环面的拓扑变换(如内外翻转.扭曲等),帮助我们直观地理解拓扑不变量和同胚等概念: 此外,也可以模拟磁场线在环面导体 ...
- Abp vNext 入门到放弃系列
文章目录 1.模块介绍 2.模块加载机制 3.依赖注入 4.AutoMapper-- 待定 5.本地化--待定 6.模型验证--待定 7.异常处理--待定 8.缓存 9.动态代理和拦截 10.分布式锁 ...
- (系列十二)Vue3+.Net8实现用户登录(超详细登录文档)
说明 该文章是属于OverallAuth2.0系列文章,每周更新一篇该系列文章(从0到1完成系统开发). 该系统文章,我会尽量说的非常详细,做到不管新手.老手都能看懂. 说明:OverallAuth2 ...
- 性能调优、虚拟机、垃圾回收、软硬件协调相关文章和视频 — Part1
本文由 ImportNew - 顾星竹 翻译自 javacodegeeks.如需转载本文,请先参见文章末尾处的转载要求. ImportNew注:如果你也对Java技术翻译分享感兴趣,欢迎加入我们的 J ...
- SAX,DOM,JAXP,JDOM,DOM4J比较分析
第一:首先介绍一下SAX,DOM,JAXP,JDOM,DOM4J的基本知识:(注意:至于 JAXP JAXB JAXM JAXR JAX-RPC 分别指什么,查看http://gceclub.sun. ...
- k8s之集群部署(kubeadm)
[master&node] 1.修改主机名 hostnamectl set-hostname master-01 cat >> /etc/hosts << EOF 17 ...
- 同步工具之Vector
官网: https://vector.dev/ 用于构建可观察性管道的轻量级.超快速工具 [安装] curl --proto '=https' --tlsv1.2 -sSf https://sh.ve ...
- 新型大语言模型的预训练与后训练范式,阿里Qwen
前言:大型语言模型(LLMs)的发展历程可以说是非常长,从早期的GPT模型一路走到了今天这些复杂的.公开权重的大型语言模型.最初,LLM的训练过程只关注预训练,但后来逐步扩展到了包括预训练和后训练在内 ...