最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

ASP.NET Core中间件计算Http请求时间示例详解

来源:动视网 责编:小采 时间:2020-11-27 22:34:28
文档

ASP.NET Core中间件计算Http请求时间示例详解

ASP.NET Core中间件计算Http请求时间示例详解:ASP.NET Core通过RequestDelegate这个委托类型来定义中间件 public delegate Task RequestDelegate(HttpContext context); 可将一个单独的请求委托并行指定为匿名方法(称为并行中间件),或在类中对其进行定义。可通过Use,或在Middleware类中
推荐度:
导读ASP.NET Core中间件计算Http请求时间示例详解:ASP.NET Core通过RequestDelegate这个委托类型来定义中间件 public delegate Task RequestDelegate(HttpContext context); 可将一个单独的请求委托并行指定为匿名方法(称为并行中间件),或在类中对其进行定义。可通过Use,或在Middleware类中


ASP.NET Core通过RequestDelegate这个委托类型来定义中间件

public delegate Task RequestDelegate(HttpContext context);

可将一个单独的请求委托并行指定为匿名方法(称为并行中间件),或在类中对其进行定义。可通过Use,或在Middleware类中配置要传递给委托执行的方法(参数类型HttpContext,返回值类型Task)。

public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware);

public static IApplicationBuilder UseMiddleware<TMiddleware>(this IApplicationBuilder app, params object[] args);

通过定义一个中间件类 来计算http请求的时间,例:

public class ResponseTimeMiddleware
{
 // Name of the Response Header, Custom Headers starts with "X-" 
 private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms";
 // Handle to the next Middleware in the pipeline 
 private readonly RequestDelegate _next;
 public ResponseTimeMiddleware(RequestDelegate next)
 {
 _next = next;
 }
 public Task InvokeAsync(HttpContext context)
 {
 // Start the Timer using Stopwatch 
 var watch = new Stopwatch();
 watch.Start();
 context.Response.OnStarting(() => {
 // Stop the timer information and calculate the time 
 watch.Stop();
 var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;
 // Add the Response time information in the Response headers. 
 context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString();
 return Task.CompletedTask;
 });
 // Call the next delegate/middleware in the pipeline 
 return this._next(context);
 }
}

总结

文档

ASP.NET Core中间件计算Http请求时间示例详解

ASP.NET Core中间件计算Http请求时间示例详解:ASP.NET Core通过RequestDelegate这个委托类型来定义中间件 public delegate Task RequestDelegate(HttpContext context); 可将一个单独的请求委托并行指定为匿名方法(称为并行中间件),或在类中对其进行定义。可通过Use,或在Middleware类中
推荐度:
标签: 示例 http core
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top