ASP.NET Core中间件计算Http请求时间示例详解
ASP.NETCore通过RequestDelegate这个委托类型来定义中间件
publicdelegateTaskRequestDelegate(HttpContextcontext);
可将一个单独的请求委托并行指定为匿名方法(称为并行中间件),或在类中对其进行定义。可通过Use,或在Middleware类中配置要传递给委托执行的方法(参数类型HttpContext,返回值类型Task)。
publicstaticIApplicationBuilderUse(thisIApplicationBuilderapp,Func,Task>middleware); publicstaticIApplicationBuilderUseMiddleware (thisIApplicationBuilderapp,paramsobject[]args);
通过定义一个中间件类来计算http请求的时间,例:
publicclassResponseTimeMiddleware { //NameoftheResponseHeader,CustomHeadersstartswith"X-" privateconststringRESPONSE_HEADER_RESPONSE_TIME="X-Response-Time-ms"; //HandletothenextMiddlewareinthepipeline privatereadonlyRequestDelegate_next; publicResponseTimeMiddleware(RequestDelegatenext) { _next=next; } publicTaskInvokeAsync(HttpContextcontext) { //StarttheTimerusingStopwatch varwatch=newStopwatch(); watch.Start(); context.Response.OnStarting(()=>{ //Stopthetimerinformationandcalculatethetime watch.Stop(); varresponseTimeForCompleteRequest=watch.ElapsedMilliseconds; //AddtheResponsetimeinformationintheResponseheaders. context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME]=responseTimeForCompleteRequest.ToString(); returnTask.CompletedTask; }); //Callthenextdelegate/middlewareinthepipeline returnthis._next(context); } }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。