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. Java面试真题之中级进阶(线程,进程,序列化,IO流,NIO)

    前言 本来想着给自己放松一下,刷刷博客,慕然回首,线程.程序.进程?Java 序列化?Java 中 IO 流? Java IO与 NIO的区别(补充)?似乎有点模糊了,那就大概看一下Java基础面试题 ...

  2. C++处理系统相关权限问题

    1.给某个文件或文件夹赋予特定用户的特定访问权限 /* 给文件(夹)szPath设置用户名为pszAccount的可读可写可修改权限 */ bool GiveTheAccountPrivToFile( ...

  3. 如何在国内使用gcr.io镜像进行拉取

    [root@k8scloude2 ~]# docker pull gcr.io/google-samples/microservices-demo/emailservice:v0.4.0 换成 [ro ...

  4. 11.Kubernetes控制器Controller详解

    Kubernetes控制器Controller详解 Statefulset Statefulset主要是用来部署有状态应用 对于StatefulSet中的Pod,每个Pod挂载自己独立的存储,如果一个 ...

  5. Air780E量产binpkg文件如何获取

    ​ 今天我们学习Air780E量产binpkg文件如何获取: 一.背景 最近luatos开发客户增多,客户在量产烧录的时候需要binpkg文件,但是有些客户不知道binpkg文件是什么,在哪里获取,是 ...

  6. gal game 杂谈——前言

    gal game 杂谈--前言 大年三十凌晨(早上)打算开始写了吧,作为第一篇先写一些前言好了. 第一次接触gal game还是在B站上看到有人玩<我和她的世界末日>当时觉得挺有意思的,加 ...

  7. ARC151C 01 Game

    ARC151C 01 Game 题目链接:ARC151C 01 Game \(SG\) 函数好题. 思路 考虑把原问题分成多个区间的不同问题,求 \(SG\) 在异或起来. 设: 1.\(SG_1(l ...

  8. 通过su - userName 切换用户,无法通过userdel -r 删除用户?

    需要通过exit退出用户,su只是进行了切换,并没有关闭

  9. 在Windows下为CodeBlocks20.3安装、配置wxWidget3.2.6

    0.前言 CodeBlocks是使用C++编写程序的一个很好的开发环境,最大的好处是它是开源的.免费的,而不仅仅是因为它具有跨平台的能力.还有一个很重要的原因是在CodeBlocks中可以使用wxWi ...

  10. 使用Tailwind CSS的几个小Tips

    前情 Tailwind CSS 是一个原子类 CSS 框架,它将基础的 CSS 全部拆分为原子级别.它的工作原理是扫描所有 HTML 文件.JavaScript 文件以及任何模板中的 CSS 类名,然 ...