1、使用中间件(Middleware)进行异常处理
public class ExceptionHandler { private readonly RequestDelegate _next; public ExceptionHandler(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { await _next.Invoke(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private async Task HandleExceptionAsync(HttpContext context, Exception exception) { var response = context.Response; response.ContentType = "application/json"; response.StatusCode = (int)HttpStatusCode.InternalServerError; await response.WriteAsync(JsonConvert.SerializeObject(new { // 直接输出异常信息,如需记录日志等操作,改这就可以 error = new { message = exception.Message, exception = exception.GetType().Name } })); } }
在Startup.cs中Configure方法注册中间件:
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseMiddleware<ExceptionHandler>();
2、使用过滤器(Filter)处理异常
public class MyUnhandledExceptionFilter : ActionFilterAttribute, IExceptionFilter { public void OnException(ExceptionContext context) { // 直接输出异常信息,如需记录日志等操作,改这就可以 context.Result = new BadRequestObjectResult(context.Exception.Message); // 直接输出异常信息,如需记录日志等操作,改这就可以 } }
在Startup.cs中ConfigureServices方法注册过滤器:
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseMiddleware<ExceptionHandler>();