Global exception handling in asp.net core webapi
2018-01-12 11:15
886 查看
在.NET Core中MVC和WebAPI已经组合在一起,都继承了Controller,但是在处理错误时,就很不一样,MVC返回错误页面给浏览器,WebAPI返回Json或XML,而不是HTML。UseExceptionHandler中间件可以处理全局异常
打开ValuesController.cs,修改代码,手动抛出一个异常
运行应用程序你应该可以看到
另一种方式是使用IExceptionFilter
最后在Startup.cs ConfigureServices方法中添加我们的过滤器
在这篇文章中我们使用了内置的中间件和内置的异常过滤器处理异常。
app.UseExceptionHandler(options => { options.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; var ex = context.Features.Get<IExceptionHandlerFeature>(); if (ex != null) { //TODO 定制响应结构的一致性 string text = JsonConvert.SerializeObject(new { message = ex.Error.Message }); await context.Response.WriteAsync(text); } }); });
打开ValuesController.cs,修改代码,手动抛出一个异常
[HttpGet] public IEnumerable<string> Get() { int a= 1; int b = a / 0; return new string[] { "value1", "value2" }; }
运行应用程序你应该可以看到
另一种方式是使用IExceptionFilter
public class CustomExceptionFilter : Microsoft.AspNetCore.Mvc.Filters.IExceptionFilter { public void OnException(ExceptionContext context) { context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.HttpContext.Response.ContentType = "application/json"; var ex = context.Exception; if (ex != null) { //TODO 定制响应结构的一致性 string text = JsonConvert.SerializeObject(new { message = ex.Message }); context.HttpContext.Response.WriteAsync(text); } } }
最后在Startup.cs ConfigureServices方法中添加我们的过滤器
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add(typeof(CustomExceptionFilter)); }); }
在这篇文章中我们使用了内置的中间件和内置的异常过滤器处理异常。
相关文章推荐
- Exception Handling in ASP.NET Web API
- C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志
- Handling HTTP 404 Error in ASP.NET Web API
- Using MongoDB with Web API and ASP.NET Core
- Asp.Net Core WebAPI入门整理(二)简单示例
- ASP.NET Core WebApi 返回统一格式参数(Json 中 Null 替换为空字符串)
- ASP.Net Core WebApi几种版本控制对比
- Adding the Test API in The ASP.NET Web API Help Page
- asp.net core webapi文件上传
- 在ASP.NET Core Web API上使用Swagger提供API文档
- Content Negotiation in ASP.NET Web API
- Asp.net Core WebApi--(1)环境搭建
- ASP.NET Core的身份认证框架IdentityServer4--(2)API跟WEB端配置
- Asp.net Core WebApi 返回JSON自动驼峰格式化问题
- Error Handling in ASP.NET Core
- Asp.Net Core WebAPI入门整理(三)跨域处理
- basic-http-authentication-in-asp-net-web-api-using-message-handlers asp.net mvc4 web api authentication
- Model Validation in ASP.NET Web API By Mike Wasson|July 20, 2012 268 of 294 people found this helpful
- Gitlab CI 自动部署 asp.net core web api 到Docker容器
- Log message Request and Response in ASP.NET WebAPI