【.NETCORE】中间件与中间件扩展

中间件是被组装成一个应用程序管道来处理请求和响应的软件组件。

每个组件选择是否传递给管道中的下一个组件的请求,并能之前和下一组分在管道中调用之后执行特定操作。

具体如图:


自己中间件类:

//自己写的中间件
    public class RequestSetOptionsMiddleware
    {
        private readonly RequestDelegate next;
        private readonly IOptions<AppOptions> options;

        public  RequestSetOptionsMiddleware(RequestDelegate next,IOptions<AppOptions> options)
        {
            this.next = next; // 下一个中间件
            this.options = options;//
        }
        //系统会自动调用
        public async Task Invoke(HttpContext httpContext)
        {
            Console.WriteLine("Invoke");
            var option = httpContext.Request.Query["optiuon"];
            if (string.IsNullOrWhiteSpace(option))
            {
                await httpContext.Response.WriteAsync("this is test");
                options.Value.Option = WebUtility.HtmlEncode(option);

            }
            else {
                await next(httpContext);
            }
        }
    }

 

中间件集扩展类:

//自定义扩展中间件-可在这里调用自己的中间件
    public static class RequestSetOptionsExtensions
    {
        public static IApplicationBuilder UseRequestSetOptions(this IApplicationBuilder app)
        {
            app.UseMiddleware<RequestSetOptionsMiddleware>();//使用中间件
            return app;
        }
    }

 

Startup->Configure中调用扩展的中间件集:

  

 

 

启动项目:
 

 

页面打印出中间件中输出的文字,说明中间件调用成功

 

 

posted @ 2021-04-08 23:51  LBO.net  阅读(162)  评论(0编辑  收藏  举报
//返回顶部