ASP.NET Core中间件:记录请求执行耗时

中间件类似以前的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运行项目,页面最下方就会插入耗时内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值