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 模型状态 处理 ...
随机推荐
- 从零开始学逆向CTF比赛,免费参加,欢迎来玩!
大家好,我是轩辕. 告诉大家一个好消息:我准备了一次逆向CTF比赛,面向所有人开放,无需购买课程,优秀的小伙伴还有奖励,参赛方式在文末会介绍,欢迎大家一起来玩. 举办这次CTF比赛,是为了检验大家从零 ...
- 网络与并行计算国际会议IFIP NPC 2024(CCF推荐会议)投稿延期至2024年8月25日
原地址: https://mp.weixin.qq.com/s/zmg0SDbyDmoNBbJYzDjADA 主页: https://www.npc-conference.com/#/npc2024/ ...
- 基于Java+SpringBoot+Mysql实现的古诗词平台功能设计与实现七
一.前言介绍: 1.1 项目摘要 随着信息技术的迅猛发展和数字化时代的到来,传统文化与现代科技的融合已成为一种趋势.古诗词作为中华民族的文化瑰宝,具有深厚的历史底蕴和独特的艺术魅力.然而,在现代社会中 ...
- Groovy基础语法!
Groovy是什么语言? Groovy是一种基于JVM(Java虚拟机)的敏捷开发语言,它结合了Python.Ruby和Smalltalk的许多强大的特性,Groovy 代码能够与 Java 代码很好 ...
- pycharm配置默认镜像地址
使用pycharm编写接口自动化测试时,需要下载很多安装包,不指定镜像时下载可能很慢,可以设置默认镜像 命令:pip config set global.index-url 镜像地址 查看已设置的默认 ...
- springboot~jpa优雅的处理isDelete的默认值
如果多个实体类都有 isDelete 字段,并且你希望在插入时为它们统一设置默认值,可以采取以下几种方法来减少代码重复: 1. 使用基类(抽象类) 创建一个基类,其中包含 isDelete 字段和 @ ...
- shell最简单的办法实现进度条
一直很好奇shell命令行安装脚本的时候怎么实现自动增长进度条而且不增加新输出的问题.以前一直觉得是不断print出来东西,但是已经输出到命令行终端的为什么也能被覆盖呢,于是看到别人写的进度条,不断尝 ...
- TIKZ——LaTeX基本绘图
TIKZ是LaTeX的一个绘图包,可以绘制其他软件很难画出来的图像. 基本用法 直线.垂足.矩形.椭圆 代码: \documentclass{article} \usepackage{tikz} \u ...
- (Python基础教程之十五)Python开箱Tuple–太多值无法解压
Python示例,用于unpack元组或序列或可迭代,以便该元组可能长于N个元素,从而导致" 太多的值无法unpack "异常. 1.打开任意长度的元组 Python" ...
- java——棋牌类游戏五子棋(singlewzq1.0)之一
这是本人最近一段时间写的五子棋的java代码,大体框架都实现了,一些细节还需要优化. package basegame; import java.awt.Color; import java.awt. ...