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. 查看一个package是否在执行

    select a.type, a.owner, b.SID, b.SERIAL#, b.OSUSER, b.MACHINE, b.PROGRAM, b.MODULE, b.ACTION From db ...

  2. 敏捷开发:Sprint Planning 冲刺计划会议详细介绍和用户故事拆分、开发任务细分

    Sprint Planning 冲刺计划会议简介 Sprint Planning (冲刺计划会议),又叫规划会议.此会议通过 Scrum 团队的集体沟通讨论,确定接下来的 Sprint 中要完成的待开 ...

  3. 基于nginx的tomcat负载均衡和集群(超简单)

    今天看到"基于apache的tomcat负载均衡和集群配置 "这篇文章成为javaEye热点. 略看了一下,感觉太复杂,要配置的东西太多,因此在这里写出一种更简洁的方法. 要集群t ...

  4. 使用 LLVM 框架创建一个工作编译器,第 1 部分

    使用 LLVM 及其中间表示构建一个自定义编译器 LLVM 编译器基础架构提供了一种强大的方法来优化您使用任何编程语言编写的应用程序.了解本系列文章(由两部分组成)第一部分中有关 LLVM 的基础知识 ...

  5. Python打包工具之pyinstaller

    前言: 近期使用PySimpleGUI开发了一款开发者工具X-助手工具,意打造成平常开发助手,无论是图片还是网址的处理等等都需要这一个工具即可,无需在网上找各个网站去找解决方案, 对于GUI的打包工具 ...

  6. Linux只gz文件格式压缩与解压缩

    压缩成gz gzip * gzip file 具体参数可使用help查看 解压缩gz gunzip * gunzip file.gz 具体也是可以用help查看

  7. msde2000的关于无法访问lonle实例的master数据库恢复

    某次关机重启后,lonele数据库实例无法访问,查看发现相应的服务(MSSQL$LONELE2.SQLAgent$LONELE2)无法启动. --------------------------- 服 ...

  8. Codeforces Round 895 (Div. 3)

    B. The Corridor or There and Back Again 题解 考虑二分答案 \(check\)时判断是否\(s_i \leq 2*(k - d_i),k\geq d_i\) c ...

  9. Natasha v9.0 为 .NET 开发者提供 [热执行] 方案.

    项目简介 自 Natasha v9.0 发布起,我将基于 Natasha 的推出热执行方案,这项技术允许基于 控制台(Console) 和新版 Asp.net Core 架构的项目在运行中动态重编译, ...

  10. 构建交互式聊天界面:react-chat-element 实战小计

    react聊天组件库:react-chat-elements 需求场景:用户可以通过多元的用户交互方式,如文件.图片.声音以及文字等输入相关信息,AI给出对应的回答 react-chat-elemen ...