asp.net webapi 404/或无效控制器/或无效请求 截取处理统一输出格式
public static class PreRouteHandler
{
public static void HttpPreRoute(this HttpConfiguration config)
{
config.Services.Replace(typeof(IHttpActionInvoker), new HttpWebApiControllerActionInvoker());
config.Services.Replace(typeof(IHttpControllerSelector), new HttpNotFoundDefaultHttpControllerSelector(config));
config.Services.Replace(typeof(IHttpActionSelector), new HttpNotFoundControllerActionSelector());
}
}
public class HttpNotFoundDefaultHttpControllerSelector : DefaultHttpControllerSelector
{
JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
public HttpNotFoundDefaultHttpControllerSelector(HttpConfiguration configuration)
: base(configuration)
{
}
public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
HttpControllerDescriptor decriptor = null;
try
{
decriptor = base.SelectController(request);
}
catch (HttpResponseException ex)
{
var code = ex.Response.StatusCode;
var result = new OutResult() { code = OutCode.失败, msg = "无效请求" };
if (code == HttpStatusCode.NotFound || code == HttpStatusCode.MethodNotAllowed)
{
ex.Response.Content = new ObjectContent(typeof(OutResult), result, formatter);
}
ex.Response.StatusCode = HttpStatusCode.OK;
throw;
}
return decriptor;
}
}
public class HttpNotFoundControllerActionSelector : ApiControllerActionSelector
{
JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
{
HttpActionDescriptor decriptor = null;
try
{
decriptor = base.SelectAction(controllerContext);
}
catch (HttpResponseException ex)
{
var code = ex.Response.StatusCode;
var result = new OutResult() { code = OutCode.失败, msg = "无效请求" };
if (code == HttpStatusCode.NotFound || code == HttpStatusCode.MethodNotAllowed)
{
ex.Response.Content = new ObjectContent(typeof(OutResult), result, formatter);
}
ex.Response.StatusCode = HttpStatusCode.OK;
throw ex;
}
return decriptor;
}
}
public class HttpWebApiControllerActionInvoker : ApiControllerActionInvoker
{
JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
var responseMessage = base.InvokeActionAsync(actionContext, cancellationToken);
if (responseMessage.Exception != null)
{
var baseException = responseMessage.Exception.InnerExceptions[0];
var result = new OutResult() { code = OutCode.失败, msg = "无效请求" };
if (baseException is TimeoutException)
{
result.code = OutCode.请求超时;
result.msg = "请求超时";
}
return Task.Run(() => new HttpResponseMessage()
{
Content = new ObjectContent(typeof(OutResult), result, formatter),
StatusCode = HttpStatusCode.OK
}, cancellationToken);
}
return responseMessage;
}
}
WebApiConfig中:
public static void Register(HttpConfiguration config)
{
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json"));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
new Newtonsoft.Json.Converters.IsoDateTimeConverter()
{
DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
}
);
config.Filters.Add(new OutResultAttribute());
config.Filters.Add(new GlobalExceptionFilter());
config.EnableCors();
// Web API 配置和服务
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.HttpPreRoute();//此处新增
}
asp.net webapi 404/或无效控制器/或无效请求 截取处理统一输出格式的更多相关文章
- 【开源】分享一个前后端分离方案-前端angularjs+requirejs+dhtmlx 后端asp.net webapi
一.前言 半年前左右折腾了一个前后端分离的架子,这几天才想起来翻出来分享给大家.关于前后端分离这个话题大家也谈了很久了,希望我这个实践能对大家有点点帮助,演示和源码都贴在后面. 二.技术架构 这两年a ...
- 前端angularjs+requirejs+dhtmlx 后端asp.net webapi
享一个前后端分离方案源码-前端angularjs+requirejs+dhtmlx 后端asp.net webapi 一.前言 半年前左右折腾了一个前后端分离的架子,这几天才想起来翻出来分享给大家 ...
- Asp.Net WebApi核心对象解析(下篇)
在接着写Asp.Net WebApi核心对象解析(下篇)之前,还是一如既往的扯扯淡,元旦刚过,整个人还是处于晕的状态,一大早就来处理系统BUG,简直是坑爹(好在没让我元旦赶过来该BUG),队友挖的坑, ...
- Asp.Net WebApi核心对象解析(上篇)
生活需要自己慢慢去体验和思考,对于知识也是如此.匆匆忙忙的生活,让人不知道自己一天到晚都在干些什么,似乎每天都在忙,但又好似不知道自己到底在忙些什么.不过也无所谓,只要我们知道最后想要什么就行.不管怎 ...
- ASP.NET WebApi 文档Swagger深度优化
本文版权归博客园和作者吴双本人共同所有,转载和爬虫请注明博客园蜗牛原文地址,cnblogs.com/tdws 写在前面 请原谅我这个标题党,写到了第100篇随笔,说是深度优化,其实也并没有什么深度 ...
- ASP.NET WebApi 文档Swagger中度优化
本文版权归博客园和作者吴双本人共同所有,转载和爬虫请注明原文地址:www.cnblogs.com/tdws 写在前面 在后台接口开发中,接口文档是必不可少的.在复杂的业务当中和多人对接的情况下,简 ...
- ASP.NET WebAPi之断点续传下载(中)
前言 前情回顾:上一篇我们遗留了两个问题,一个是未完全实现断点续传,另外则是在响应时是返回StreamContent还是PushStreamContent呢?这一节我们重点来解决这两个问题,同时就在此 ...
- ASP.NET WEBAPI 的身份验证和授权
定义 身份验证(Authentication):确定用户是谁. 授权(Authorization):确定用户能做什么,不能做什么. 身份验证 WebApi 假定身份验证发生在宿主程序称中.对于 web ...
- 使用Asp.net WebAPI 快速构建后台数据接口
现在的互联网应用,无论是web应用,还是移动APP,基本都需要实现非常多的数据访问接口.其实对一些轻应用来说Asp.net WebAPI是一个很快捷简单并且易于维护的后台数据接口框架.下面我们来快速构 ...
随机推荐
- arcgisengine实现矩形转面
面文件都有几何类型. arcengine在绘图时,不规则的多边形的几何类型是esriGeometryPolygon,矩形的几何类型是esriGeometryEnvelope,圆的几何类型是esriGe ...
- EF-CodeFirst-基础
什么是Code-First Code-First主要用于领域驱动设计.在Code-First方法中,专注于应用程序的域,先开始为域实体创建类,而不是先设计数据库,然后创建与数据库设计相匹配的类.下图说 ...
- 获取 base64 的封装
/** * 1. 如何实例化 const fileInput = await FileInput.init(fileInputEle, isMulFile) */ export class FileI ...
- 1-2-编译U-boot
1-2-编译U-boot 1.su+enter进入超级用户模式. 2.cd /mnt/+两次Tab去到根目录,ls显示共享文件夹里的文件. 3.解压tar xvfj uboot_TQ210_1.3.4 ...
- yaml语言在线可视化翻译
yaml语言在线可视化翻译 https://editor.swagger.io/
- docker端口映射或启动容器时报错
原始镜像如下: REPOSITORY TAG IMAGE ID CREATED SIZE xtjatswc/mycore2 v3 73ce3cd97c01 About an hour ago .74G ...
- 前端框架之Vue(10)-全家桶简单使用实例
vue-router官方文档 vuex官方文档 安装 npm install vue-router --save 使用实例 vue-router初使用(webpack-simple模板) 1.切换到指 ...
- padStart()方法,padEnd()方法
https://blog.csdn.net/ixygj197875/article/details/79090578
- 装系统w7、ubuntu、centos等系统(一)
装w7系统准备 1.从老毛桃u盘启动盘制作工具_老毛桃u盘装系统_老毛桃pe_老毛桃官网下载装机版 2.一个正常使用的U盘,但容量大于4G,并且插入电脑保持连接 3.老毛桃装机版选择U盘启动-> ...
- python----GIL的概念
问题:多核没有利用上 GIL:全局解释锁 因为有GIL ,所以同一时刻,只有一个线程被CPU执行 任务:IO密集型,计算密集型 对于IO密集型的任务:python的多线程的是有意义的 可以采用多进程+ ...