Web API学习笔记(五)——中间件(Middleware)和HTTP请求管线(Http Request Pipeline)

1.HTTP请求管线(Http Request Pipeline)

在这里插入图片描述
在这里插入图片描述

2.中间件(Middleware)

2.1概述

1.中间件是HTTP请求管线中使用的一段代码
2.Asp .Net Core应用程序可以有n个中间件
3.中间件的顺序在执行过程中非常重要。

中间件例如:
1.Routing
2.Authentication
3.Add excretion page …

2.2Run(),Use(),Next()和Map()在中间件中的使用

1.Run()方法用于完成中间件的执行
2.Use()方法用于在管线中插入新的中间件
3.Next()方法用于将执行传递给下一个中间件
4.Map()方法用于将中间件映射到特定的URL

2.2.1 Run()方法

添加一个终端中间件委托到应用到请求管线。

IApplicationBuilder.Run(RequestDelegate handler)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
   
   
            app.Run(async (context) =>
            {
   
   
                await context.Response.WriteAsync("hello Run");
            });

            app.Run(async (context) =>
            {
   
   
                await context.Response.WriteAsync("hello Run2");
            });


            if (env.IsDevelopment())
            {
   
   
                app.UseDeveloperExceptionPage();
            }


            app.UseRouting();

            app.UseEndpoints(endponits =>
            {
   
   
                endponits.MapControllers();
            });
        }

运行结果:
在这里插入图片描述

2.2.1 Use()&Next()
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
   
   
            //app.Run(async (context) =>
            //{
   
   
            //    await context.Response.WriteAsync("hello Run");
            //});

            app.Use(async (context,next) =>
            {
   
   
                await context.Response.WriteAsync("hello Use1 \n");
            });

            app.Run(async (context) =>
            {
   
   
                await context.Response.WriteAsync("hello Run2");
            });


            if (env.IsDevelopment())
            {
   
   
                app.UseDeveloperExceptionPage();
            }


            app.UseRouting();

            app.UseEndpoints(endponits =>
            {
   
   
                endponits.MapControllers();
            });
        }

运行结果:
在这里插入图片描述

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
   
   
            //app.Run(async (context) =>
            //{
   
   
            //    await context.Response.WriteAsync("hello Run");
            //});

            app.Use(async (co
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值