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();//此处新增
}




本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/p/6876970.html,如需转载请自行联系原作者

相关文章
|
7天前
|
开发框架 监控 前端开发
在 ASP.NET Core Web API 中使用操作筛选器统一处理通用操作
【9月更文挑战第27天】操作筛选器是ASP.NET Core MVC和Web API中的一种过滤器,可在操作方法执行前后运行代码,适用于日志记录、性能监控和验证等场景。通过实现`IActionFilter`接口的`OnActionExecuting`和`OnActionExecuted`方法,可以统一处理日志、验证及异常。创建并注册自定义筛选器类,能提升代码的可维护性和复用性。
|
2月前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
36 0
|
2月前
|
存储 开发框架 .NET
ASP.NET Web Api 使用 EF 6,DateTime 字段如何取数据库服务器当前时间
ASP.NET Web Api 使用 EF 6,DateTime 字段如何取数据库服务器当前时间
|
2月前
|
开发框架 .NET API
如何在 ASP.NET Core Web Api 项目中应用 NLog 写日志?
如何在 ASP.NET Core Web Api 项目中应用 NLog 写日志?
|
2月前
|
开发框架 .NET API
分享一个 ASP.NET Web Api 上传和读取 Excel的方案
分享一个 ASP.NET Web Api 上传和读取 Excel的方案
|
29天前
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
28 7
|
27天前
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
38 0
|
2月前
|
开发框架 前端开发 安全
ASP.NET MVC 如何使用 Form Authentication?
ASP.NET MVC 如何使用 Form Authentication?
|
2月前
|
开发框架 .NET
Asp.Net Core 使用X.PagedList.Mvc.Core分页 & 搜索
Asp.Net Core 使用X.PagedList.Mvc.Core分页 & 搜索
93 0
|
5月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
159 0
下一篇
无影云桌面