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的更多相关文章

  1. webapi Model Validation 模型验证

    通常情况下,对于那些经常为别人提供数据接口的开发人员来说,对于调用方传递过来的参数都会有验证处理.例如: if (string.IsNullOrEmpty(entity.Name)) { //当姓名为 ...

  2. webapi中的模型验证

    mic: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-valida ...

  3. sencha touch Model validations(模型验证,自定义验证)

    model Ext.define('app.model.Register', { extend: 'Ext.data.Model', requires: ['Ext.data.JsonP'], con ...

  4. 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)

    一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...

  5. 一、WebApi模型验证

    一.新建项目 选择空的项目webapi 查看启动端口 创建控制器 添加方法 public class VerifController : ApiController { public IHttpAct ...

  6. webapi - 模型验证

    本次要和大家分享的是webapi的模型验证,讲解的内容可能不单单是做验证,但都是围绕模型来说明的:首先来吐槽下,今天下午老板为自己买了套新办公家具,看起来挺好说明老板有钱,不好的是我们干技术的又成了搬 ...

  7. ASP.NET Core 6.0 基于模型验证的数据验证

    1 前言 在程序中,需要进行数据验证的场景经常存在,且数据验证是有必要的.前端进行数据验证,主要是为了减少服务器请求压力,和提高用户体验:后端进行数据验证,主要是为了保证数据的正确性,保证系统的健壮性 ...

  8. Web API中的模型验证

    一.模型验证的作用 在ASP.NET Web API中,我们可以使用 System.ComponentModel.DataAnnotations 命名空间中的属性为模型上的属性设置验证规则. 一个模型 ...

  9. webapi中使用token验证(JWT验证)

    本文介绍如何在webapi中使用JWT验证 准备 安装JWT安装包 System.IdentityModel.Tokens.Jwt 你的前端api登录请求的方法,参考 axios.get(" ...

  10. ASP.NET Core 中文文档 第四章 MVC(2.2)模型验证

    原文:Model Validation 作者:Rachel Appel 翻译:娄宇(Lyrics) 校对:孟帅洋(书缘) 在这篇文章中: 章节: 介绍模型验证 验证 Attribute 模型状态 处理 ...

随机推荐

  1. 推荐一个.NetCore开源的CMS项目,功能强大、扩展性强、支持插件的系统!

    推荐一个基于.Net Core开发的开源CMS项目,该项目功能完善.涉及知识点比较多,不管是作为二次开发.还是学习都是不错的选择. 01 项目简介 Cofoundry是基于.Net开发的.代码优先开发 ...

  2. 卸载php8后导致php7.4不能被apache解析了

    今天突然发现web页面不能解析了,直接返回php代码了,想起来可能是由于不小心更新过apt 源,有一次安装了php8,后来又卸载,导致的,查了一下,发现是libapache2-mod-php没安装. ...

  3. ES6 延展操作符

    延展操作符(Spread operator) 延展操作符 = ...可以在函数调用/数组构造时,将数组表达式或者string在语法层面展开,还可以在构造对象时,将对象表达式按key-value的方式展 ...

  4. Five minute introduction to ANTLR 3

    What is ANTLR 3? ANTLR - ANother Tool for Language Recognition - is a tool that is used in the const ...

  5. PHP之常见问题

    汇总在PHP开发中遇到的一些问题 1.post提交参数缺失 场景: 在前端页面发起一个post提交的时候,查看payload中的数据是正常的, 但是在接收的时候,发现只有部分数据,算了一下,包含的数据 ...

  6. golang之jwt

    golang-jwt是go语言中用来生成和解析jwt的一个第三方库.本文中使用目前最新的v5版本. 安装 go get -u github.com/golang-jwt/jwt/v5 在代码中引用 i ...

  7. pycharm集成Jupyter Notebook

    1. Jupyter Notebook Jupyter项目是一个非盈利的开源项目,源于 2014 年的 ipython 项目,支持运行 40 多种编程语言.Jupyter Notebook 的本质是一 ...

  8. django插件之django-import-export

    文档:https://django-import-export.readthedocs.io/en/latest/getting_started.html#creating-import-export ...

  9. C#委托的前世今生

    一.前言 大家好!我是付工. 十年前,刚开始学C#编程的时候,被委托困扰了很久. 今天跟大家分享一下关于委托的那些事儿. 二.委托原理 什么是委托? 抛开编程,委托是一个汉语词语,指的是把事情托付给别 ...

  10. Java并发 —— 线程并发(一)

    线程和进程 进程就是一个内存中运行的应用程序 线程是当前进程中的一个执行任务(控制单元),负责当前进程中程序的执行 区别与联系 根本区别:进程是操作系统资源分配的基本单位,线程是处理器任务调度和执行的 ...