一、过滤器方式
先定义一个异常过滤器
/// <summary> /// 异常过滤器 /// </summary> public class ExceptionFilter : IExceptionFilter { /// <summary> /// 发生异常时进入 /// </summary> /// <param name="context"></param> public void OnException(ExceptionContext context) { if (context.ExceptionHandled == false) { context.Result = new ContentResult { Content = context.Exception.Message,//这里是把异常输出,也可以不输出,也可以输出JSON结构的字符串。 StatusCode = StatusCodes.Status200OK, ContentType = "text/html;charset=utf-8" }; } context.ExceptionHandled = true; //写入日志,或者其它操作 } }
再API控制器使用过滤器
[TypeFilter(typeof(ExceptionFilter))]//这里使用自定义过滤器 [ApiController] public class MyController:ControllerBase { //..... }
二、配置方式
在 Startup.cs 中的, Configure 配置中
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //异常配置文件写法 if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(config => { config.Run(async context => { context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; var error = context.Features.Get<IExceptionHandlerFeature>(); if (error != null) { var ex = error.Error; //输出异常内容,也可以不输出,也可以输出JSON结构的字符串 await context.Response.WriteAsync(ex.Message); } }); }); } }
三、中间件方式
先定义一个异常中间件
public class CustomExceptionMiddleware { private readonly RequestDelegate _next; //private readonly ILogger<CustomExceptionMiddleware> _logger; public CustomExceptionMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext httpContext) { try { await _next(httpContext); } catch (Exception ex) { //写入日志或者其它操作 //log await HandleExceptionAsync(httpContext, ex); } } private async Task HandleExceptionAsync(HttpContext httpContext, Exception ex) { httpContext.Response.StatusCode = StatusCodes.Status200OK; httpContext.Response.ContentType = "application/json;charset=utf-8"; //输出异常内容 await httpContext.Response.WriteAsync(ex.Message); //如果不输出,则需要下面这句 //return Task.CompletedTask; } }
再定义一个扩展类
public static class CustomExceptionMiddlewareExtensions { public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<CustomExceptionMiddleware>(); } }
在 Startup 的 Configure 中配置
app.UseCustomExceptionMiddleware();
放在最前面