用一个简单的例子教你如何 自定义ASP.NET Core 中间件(一)

提起中间件大家一定不陌生,我们也用过.NET core很多很好用的中间件,但是如何自己写一个中间件呢,可能大部分同学不清楚怎么写,我之前也不会,看了微软官方文档 【ASP.NET Core - 中间件】感觉讲的也不是很清楚,下面就用一个简单的例子告诉大家什么是中间件,怎么自定义一个中间件。

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

  • 选择是否将请求传递到管道中的下一个组件。
  • 可在管道中的下一个组件前后执行工作。
  • 请求委托用于生成请求管道。 请求委托处理每个 HTTP 请求。

一句话总结:中间件是比筛选器更底层,更上游的面向切面技术,其性能最高,可处理的应用范围远比过滤器广,如实现网关,URL 转发,限流等等。

ASP.NET Core 请求管道包含一系列请求委托,依次调用。 下图演示了这一概念。 沿黑色箭头执行。

Request processing pattern showing a request arriving, processing through three middlewares, and the response leaving the app. Each middleware runs its logic and hands off the request to the next middleware at the next() statement. After the third middleware processes the request, the request passes back through the prior two middlewares in reverse order for additional processing after their next() statements before leaving the app as a response to the client.

每个委托均可在下一个委托前后执行操作。 应尽早在管道中调用异常处理委托,这样它们就能捕获在管道的后期阶段发生的异常,也就是把app.UseExceptionHandler();异常处理代码放在最前面注入。

先来看一些常见的简单中间件

1、所有请求返回同一个结果

app.Run(async context =>
{
    await context.Response.WriteAsync("Hello world!");
});

 

2、拦截所有请求(可多个)

            app.Use(async (context, next) =>
            {
                // 比如设置统一头
                context.Response.Headers["test1"] = "111";

                // 执行下一个中间件
                await next.Invoke();
            });

            app.Use(async (context, next) =>
            {
                // 比如设置统一头
                context.Response.Headers["test2"] = "222";

                // 执行下一个中间件
                await next.Invoke();
            });

            app.Use(async (context, next) =>
            {
                string headers = "";
                foreach (var header in context.Response.Headers)
                {
                    headers += header.Key + "=" + header.Value + "\n";
                }
                Console.WriteLine(headers);

                // 执行下一个中间件
                await next.Invoke();
            });

3、特定路由中间件(可多个)

            app.Map("/hello", app => {
                app.Run(async context =>
                {
                    await context.Response.WriteAsync("Map Test 1");
                });
            });

            app.Map("/no", app => {
                app.Run(async context =>
                {
                    await context.Response.WriteAsync("Map Test 2");
                });
            });

 

4、嵌套路由中间件(可多个)

app.Map("/level1", level1App => {
                level1App.Map("/level2a", level2AApp => {
                    app.Use(async (context, next) =>
                    {
                        // 比如设置统一头
                        context.Response.Headers["test1"] = "111";

                        // 执行下一个中间件
                        await next.Invoke();
                    });
                });
                level1App.Map("/level2b", level2BApp => {
                    app.Use(async (context, next) =>
                    {
                        string headers = "";
                        foreach (var header in context.Response.Headers)
                        {
                            headers += header.Key + "=" + header.Value + "\n";
                        }
                        Console.WriteLine(headers);

                        // 执行下一个中间件
                        await next.Invoke();
                    });
                });
            });

下一章继续教大家如何自定义一个中间件:用一个简单的例子教你如何 自定义ASP.NET Core 中间件(二)-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YuanlongWang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值