中间件类似以前的HttpModule,在请求管道中用来集中处理某些事情,比如:记日志,异常处理,权限验证等等。
中间件在Startup.cs中的Configure()方法中注册。
ASP.NET Core 请求管道执行流程。从Request开始,依次执行每个中间件的逻辑。
实例:创建ASP.NET Core Middleware(中间件),记录请求执行耗时
第1步,创建项目
第2步,创建MyMiddleware.cs
创建MyMiddleware类
public class MyMiddleware
{
private DateTime _startTime;
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
_startTime = DateTime.Now;
// Call the next delegate/middleware in the pipeline
await _next(context);
await context.Response.WriteAsync("执行耗时:" + (DateTime.Now - _startTime).TotalSeconds.ToString() + "s");
}
}
添加中间件扩展
public static class MyMiddlewareExtensions
{
public static IApplicationBuilder UseMyMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleware>();
}
}
在Startup.cs的Configure()方法中注册中间件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMyMiddleware(); //注册中间件
app.UseMvc();
}
F5运行项目,页面最下方就会插入耗时内容