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是一个很快捷简单并且易于维护的后台数据接口框架.下面我们来快速构 ...
随机推荐
- Shell实现判断进程是否存在并重新启动脚本
Shell实现判断进程是否存在并重新启动脚本 - superbfly的专栏 - CSDN博客 https://blog.csdn.net/superbfly/article/details/52513 ...
- java中组合与聚合(聚集)的区别
组合和聚合是有很大区别的,这个区别不是在形式上,而是在本质上: 组合:比如A类中包含B类的一个引用b,当A类的一个对象消亡时,b这个引用所指向的对象也同时消亡(没有任何一个引用指向它,成了垃圾对象) ...
- [daily][samba] smbclient使用
用的也不是太明白,反正凑合用吧. 在用之前,只得到了两个信息,1:ip 192.168.30.9. 2:可以免密登录. 1. 用这个命令看一看,主要是找到这个目录:Anonymous ┬─[t ...
- python之路(转载)
Python之路 Python生产环境部署(fastcgi,uwsgi) Django 缓存.队列(Memcached.redis.RabbitMQ) Python(九) Python ...
- LeetCode 929 Unique Email Addresses 解题报告
题目要求 Every email consists of a local name and a domain name, separated by the @ sign. For example, i ...
- 解读EXPLAIN执行计划中的key_len(转)
原文:http://imysql.com/2015/10/20/mysql-faq-key-len-in-explain.shtml 导读 EXPLAIN中的key_len一列表示什么意思,该如何解读 ...
- 内核ipc机制
内核版本:linux2.6.22.6 硬件平台:JZ2440 驱动源码 block_ipc_poll_key_int_drv.c : #include <linux/module.h> # ...
- jquery代码修改input的value值,而页面上input框的值没有改变的解决办法
问题描述: 在搜索框中输入一些字符,并且点击搜索框右边的五角星做收藏操作时,打开的弹框中Save Search:后面的input中的值被赋值了外面搜索框的值,但是当此次操作完成之后,再次做同样的操作, ...
- python-面向对象-04_面向对象封装案例
面向对象封装案例 目标 封装 小明爱跑步 存放家具 01. 封装 封装 是面向对象编程的一大特点 面向对象编程的 第一步 —— 将 属性 和 方法 封装 到一个抽象的 类 中 外界 使用 类 创建 对 ...
- 微信小程序分享支持自定义封面图
微信小程序又发布更新了,刚好昨天支付宝也发布小程序,不能让它抢了风头的节奏.微信小程序主要更新如下:“小程序分享支持自定义封面图,公众号及小程序客服可发送小程序卡片.同时,我们还开放了获取发票抬头,指 ...