所谓中间件就是用于处理httpcontext的请求,如果某个管道可以处理这个请求了,就不用再往下传递了,直接在当前管道处理完成返回。
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
IConfiguration configuration,
IWelcome iWelcome,
ILogger<Startup> logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(next =>
{
logger.LogInformation("---app.use()----");
return async httpContext =>
{
logger.LogInformation("---- async httpcontext");
if (httpContext.Request.Path.StartsWithSegments("/first"))
{
logger.LogInformation("---first---");
await httpContext.Response.WriteAsync("first!!!");
}
else
{
logger.LogInformation("---next(httpcontext----");
await next(httpContext);
}
};
});
app.UseWelcomePage(new WelcomePageOptions
{
Path = "/welcome"
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
//var welcome = configuration["welcome"];
var welcome = iWelcome.GetMessage();
await context.Response.WriteAsync(welcome);
});
});
在上面的例子中使用了app.Use()
中间件,里面实现了对输入的http的请求处理。
浏览器输入http://localhost:5000/first
浏览器输入http://localhost:5000/welcome
浏览器输入http://localhost:5000/
从这可以看出管道的作用