您的位置:首页 > 编程语言 > ASP

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中间件可以处理全局异常

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));
});
}


在这篇文章中我们使用了内置的中间件和内置的异常过滤器处理异常。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: