Global exception handling in asp.net core webapi
阿新 • • 發佈:2018-01-12
div 程序 todo color 返回 lob 文章 value config
在.NET Core中MVC和WebAPI已經組合在一起,都繼承了Controller,但是在處理錯誤時,就很不一樣,MVC返回錯誤頁面給瀏覽器,WebAPI返回Json或XML,而不是HTML。UseExceptionHandler中間件可以處理全局異常
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));
});
}
在這篇文章中我們使用了內置的中間件和內置的異常過濾器處理異常。
Global exception handling in asp.net core webapi