一、说明
关于.Net Core中间件的说明可以参考相关文档
https://www.cnblogs.com/stulzq/p/7760648.html
二、上代码
1、依赖注入
public static class DependencyInjectionExtersion { public static IApplicationBuilder UseErrorMiddlewares(this IApplicationBuilder builder) { return builder.UseMiddleware<ErrorHandlingMiddleware>(); } }
2、中间件实现
public class ErrorHandlingMiddleware { private readonly RequestDelegate _next; public ErrorHandlingMiddleware(RequestDelegate next) { this._next = next; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { var result = JsonConvert.SerializeObject(new { Code="-1",Msg=ex.Message}); context.Response.StatusCode = 200; context.Response.ContentType = "application/json;charset=utf-8"; await context.Response.WriteAsync(result); } } }
3、Startup类里面Configure方法引入中间件
// 注入异常中间件 app.UseErrorMiddlewares();
4、控制器层
public class Home1Controller : Controller { // GET: Home1Controller public ActionResult Index() { throw new System.Exception("异常了"); } }