以下是一个示例的 .NET Core 中间件,用于记录请求处理时间的情况:
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Diagnostics;
- using System.Threading.Tasks;
-
- public class TimingMiddleware
- {
- private readonly RequestDelegate _next;
- private readonly ILogger<TimingMiddleware> _logger;
-
- public TimingMiddleware(RequestDelegate next, ILogger<TimingMiddleware> logger)
- {
- _next = next;
- _logger = logger;
- }
-
- public async Task Invoke(HttpContext context)
- {
- var stopwatch = Stopwatch.StartNew();
-
- try
- {
- await _next(context);
- }
- finally
- {
- stopwatch.Stop();
- var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
- _logger.LogInformation($"Request took {elapsedMilliseconds} ms");
- }
- }
- }
-
将上述代码放在你的项目中,然后在 Startup.cs 文件的 Configure 方法中使用该中间件:
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
- {
- // ...
-
- app.UseMiddleware<TimingMiddleware>();
-
- // ...
- }
-
这样,每次请求进入中间件时,它会记录请求处理的时间,并将其记录到日志中。你可以使用项目的日志记录器(例如 ILogger<T>)进行记录,也可以使用其他日志库。
这是一个基本示例,你可以根据需要进行修改和扩展,例如记录请求的路径、HTTP 方法、响应状态码等其他有用的信息。也可以对请求时间做一些条件筛选,比如记录一些请求时间过长的请求,把请求的路径信息等记录下方便进行代码优化。