官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1

中间件的定义:中间件是组装到应用程序管道中以处理请求和响应的软件

ASP.NET Core请求流程由一系列请求委托组成,如下图:

asp.net core 自定义中间件

编写中间件:中间件编写在一个类里,并通过扩展方法暴露

1、将中间件委托移动到一个类:

    public class RequestCustomeMiddleware
    {
        private readonly RequestDelegate _next;

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

        public Task Invoke(HttpContext context)
        {
            //......
            // do something

            // Call the next delegate/middleware in the pipeline
            return this._next(context);
        }
    }

2、通过扩展方法暴露中间件:

    public static class RequestCustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseRequestCustomCulture(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestCustomMiddleware>();
        }
    }

3、在Startup类的Configure方法里调用中间件:

    public void Configure(IApplicationBuilder app)
    {
        app.UseRequestCulture();
    }

 

相关文章:

  • 2020-06-17
  • 2022-12-23
  • 2022-12-23
  • 2019-05-16
  • 2019-07-03
  • 2022-12-23
  • 2022-01-18
  • 2022-01-02
猜你喜欢
  • 2021-07-12
  • 2021-05-28
  • 2023-02-18
  • 2022-02-19
  • 2022-01-04
  • 2021-12-27
  • 2022-12-23
相关资源
相似解决方案