Asp.Net Core学习笔记5——中间件

Asp.Net Core学习笔记5——中间件

1.中间件

中间件是组装到应用程序管道中以处理请求和响应的软件 。用户每一次请求都会被放到一个请求管道,这个请求管道通过动态配置各种业务逻辑对应的中间件,从而应对不同用户做出不同的请求响应

 

2.中间件管道的处理流程

 

下面是一个简单的中间件例子:

 

复制代码
            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("First Middleware in. \r\n");
                await next.Invoke();
                await context.Response.WriteAsync("First Middleware out. \r\n");
            });

            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("Second Middleware in. \r\n");
                // 水管阻塞,封包不往后送
                var condition = false;
                if (condition)
                {
                    await next.Invoke();
                }
                await context.Response.WriteAsync("Second Middleware out. \r\n");
            });

            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("Third Middleware in. \r\n");
                await next.Invoke();
                await context.Response.WriteAsync("Third Middleware out. \r\n");
            });
复制代码

 

输出结果:

First Middleware in. 
Second Middleware in. 
Second Middleware out. 
First Middleware out. 

 

 

3.中间件使用

3.1 Run (终端中间件)

Run方法运行一个委托,在委托终止了管道的运行,输出结果"终端中间件",这种中间件称为终端中间件。在Startup.cs中有如下代码:

app.Run(async (context) =>
{
    await context.Response.WriteAsync("终端中间件");
});

//其他中间件
......

 

3.2 Map (约束终端中间件)

Map匹配短路管道,匹配HttpContext.Request.Path的预设值。

复制代码
            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("First Middleware in. \r\n");
                await next.Invoke();
                await context.Response.WriteAsync("First Middleware out. \r\n");
            });


            app.Map("/second", mapApp =>
            {
                mapApp.Use(async (context, next) =>
                {
                    await context.Response.WriteAsync("Second Middleware in. \r\n");
                    await next.Invoke();
                    await context.Response.WriteAsync("Second Middleware out. \r\n");
                });                
            });

            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("Third Middleware in. \r\n");
                await next.Invoke();
                await context.Response.WriteAsync("Third Middleware out. \r\n");
            });
复制代码

输出结果:

First Middleware in. 
Third Middleware in. 
Third Middleware out. 
First Middleware out. 

如果使用是:http://localhost:端口号/second访问,输出结果:

First Middleware in. 
Second Middleware in. 
Second Middleware out. 
First Middleware out. 

 

3.3 自定义中间件

自定义一个中间件类

复制代码
    public class RequestMiddleware
    {
        private readonly RequestDelegate _next;
        public RequestMiddleware(RequestDelegate next
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            //逻辑
            ......
            
            return _next(httpContext);
        }
    }
复制代码

添加扩展方法(使用静态方法包装)

 

    public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseRequestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestMiddleware>();
        }
    }

 

 

 

4.注册中间件

4.1 全局注册

复制代码
public void Configure(IApplicationBuilder app)
{
  //....

  app.UseMiddleware<RequestMiddleware>(); 
    
    //如果添加扩展方法,可以这样写
    //app.UseRequestMiddleware();
    
}
复制代码

4.2 局部注册

复制代码
[MiddlewareFilter(typeof(RequestMiddleware))]
public class MyController : Controller
{

    [MiddlewareFilter(typeof(RequestMiddleware))]
    public IActionResult Index()
    {
        // ...
    }
}
复制代码

 

posted @   落叶窥秋  阅读(232)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示