• ASP.NET Core 实现自定义中间件


    中间件是一种装配到应用管道以处理请求和响应的软件。 每个组件:

    • 选择是否将请求传递到管道中的下一个组件。
    • 可在管道中的下一个组件前后执行工作。

    请求委托用于生成请求管道。 请求委托处理每个 HTTP 请求。

    管道中的中间件执行逻辑如下:

    向 Startup.Configure 方法添加中间件组件的顺序定义了针对请求调用这些组件的顺序,以及响应的相反顺序。 此顺序对于安全性、性能和功能至关重要。

    知道执行顺序,也就知道我们的中间件需要添加在那个位置(不同的位置,执行顺序不同),ASP.NET Core MVC中间件执行顺序如下:

    ASP.NET Core自定义中间件构造函数参数必须有RequestDelegate委托,类中需要实现一个异步的InvokeAsync方法。

    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    
    namespace Research.Web.Middlewares
    {
        public class RequestMiddlewares
        {
            RequestDelegate _next;
            ILogger _logger;
            public RequestMiddlewares(RequestDelegate next, ILogger<RequestMiddlewares> logger)
            {
                this._next = next;
                this._logger = logger;
            }
    
            public async Task InvokeAsync(HttpContext context, IWebHostEnvironment env)
            {
                //中间件代码……
                if (context.Request.PathBase == null)
                {
                    //让请求管道短路(不在继续执行后续组件)
                    await context.Response.WriteAsync("The request failed.");
                }
                //调用管道中的下一个组件
                await _next(context);
            }
        }
    
    public static class RequestMiddlewaresrExtensions { public static IApplicationBuilder UseRequestMiddlewares(this IApplicationBuilder app) { //将中间件添加到管道中 return app.UseMiddleware<RequestMiddlewares>(); } } }

    此实列将 IWebHostEnvironment环境变量信息注入到了中间件。

    使用自定义中间件,在Startup类中的Configure方法中使用如下:

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
    
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseRouting();
    
                //自定义中间件
                app.UseRequestMiddlewares();
        }

    更加详细的中间件知识,请参考微软文档:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0

  • 相关阅读:
    python gzip get url
    nginx 日志解析,nginx缓存
    Keepalived
    SEO 搜索引擎优化
    检测网站是否支持gzip的本地代码
    使用logrotate做nginx日志轮询
    YUI Compressor下载
    Adobe Illustrator有 机会装一下
    同步时间
    买不起书啊nginx http server filetype:pdf 30刀
  • 原文地址:https://www.cnblogs.com/pudefu/p/14544802.html
Copyright © 2020-2023  润新知