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是一个很快捷简单并且易于维护的后台数据接口框架.下面我们来快速构 ...
随机推荐
- arcengine右键实现new group layer的功能
没有找到相关方法,但是有对图层组进行操作的资料. https://gis.stackexchange.com/questions/43620/how-do-i-reach-a-layer-inside ...
- create table test_create_table_CreateAs as select * from test_create_table; 表结构的破坏 复制字段结构 复制表结构 LIKE
案例中: 索引丢失.分区丢失 实际测试 Target Server Type : MYSQLTarget Server Version : 50616File Encoding : 65001 Dat ...
- lumen
HTTP路由 基本路由 路由参数 必填参数 可选参数 正则表达式约束 命名路由 路由组 中间件 命令空间 路由前缀 基本路由 你可以在 route/web.php 文件中定义应用程序的全部路由.最基本 ...
- 2015年蓝桥杯省赛A组c++第1题
/* 方程: a^2 + b^2 + c^2 = 1000 这个方程有整数解吗?有:a,b,c=6,8,30 就是一组解. 你能算出另一组合适的解吗? 请填写该解中最小的数字. 注意:你提交的应该是一 ...
- LCA&最小生成树
LCA 经常被用来使用.比如询问树两点之间的距离. 比如树上差分 都是经常被使用的类型.有的时候倍增求LCA的同时还可以优化算法. 这道题呢 求一个严格的最小生成树,当然如果不严格的话如果有重边那么就 ...
- 洛谷P3224 永无乡 [HNOI2012] 线段树/splay/treap
正解:线段树合并 解题报告: 传送门! 这题也是有很多解法,eg:splay,treap,... 然而我都不会我会学的QAQ! 反正今天就只讲下线段树合并怎么做QAQ 首先看到这样子的说第k重要的是什 ...
- SQL Server 2008 R2提示评估期已过
解决SQL Server 2008 r2提示评估期已过 1.注册表把 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\100\Co ...
- c语言数组应用
#include <stdio.h> #define SIZE 5 int main(void) { int sum[3]={0},sum2[SIZE]={0},i,sum1=0; dou ...
- gitlab数据库
event表中action对应操作: 1 - 新建项目 5 - push 8 - 在某项目中赋予某人权限 9 - 在某项目中取消某人权限
- VS Code Html Zen coding
zen coding是一种编写html和css的方法, 很快捷. 打开Views/Home/About.cshtml, 然后在空白处输入div然后按Tab: 随后完整的div标签就出来了: zen c ...