中间件

核心对象

  • IApplicationBuilder
  • RequestDelegate

代码演示

            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("hello Word");
            });

指定路径

代码演示

            app.MapWhen(context =>
            {
                return context.Request.Query.Keys.Contains("id");
            }, builder =>
            {
                builder.Use(async (context, next) =>
                {
                    await context.Response.WriteAsync("hello Word");
                });
            });

自定义中间件

中间件代码

    public class MyMiddleware
    {
        RequestDelegate _next;

        public MyMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            Console.WriteLine("===========执行前逻辑==========");
            await _next(context);
            Console.WriteLine("===========执行后逻辑==========");
        }
    }

扩展方法

    public static class MyBuilderExtensions
    {
        public static IApplicationBuilder UserMyMiddleware(this IApplicationBuilder app)
        {
            return app.UseMiddleware<MyMiddleware>();
        }
    }

Startup类注册中间件

            app.UserMyMiddleware();

异常处理中间件

代码演示

            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    IExceptionHandlerPathFeature exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
                    context.Response.ContentType = "application/json;charset=utf-8;";
                    context.Response.StatusCode = StatusCodes.Status200OK;
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(exceptionHandlerPathFeature));
                });
            });
posted @ 2020-11-06 16:34  2014吕小柯  阅读(69)  评论(0)    收藏  举报