返回顶部

.Net Core之自定义中间件

一、说明

关于.Net Core中间件的说明可以参考相关文档

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-2.1

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("异常了");
        }
    }

5、页面效果

 

posted @ 2022-03-04 17:41  SportSky  阅读(213)  评论(0编辑  收藏  举报
作者:SportSky 出处: http://www.cnblogs.com/sportsky/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如果觉得还有帮助的话,可以点一下右下角的【推荐】,希望能够持续的为大家带来好的技术文章!想跟我一起进步么?那就【关注】我吧。