.NET Core记录请求处理时间的中间件
2024-10-08
21
以下是一个示例的 .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 方法、响应状态码等其他有用的信息。也可以对请求时间做一些条件筛选,比如记录一些请求时间过长的请求,把请求的路径信息等记录下方便进行代码优化。
更新于:10天前赞一波!
相关文章
- asp.net母版页和内容页PageLoad顺序
- ASP.NET Core 2.1中的ActionResult<T>
- .NET Core 3.0创建一个单独的可执行文件
- 在ASP.NET Core 2.1中使用HttpClientFactory的3种方法
- .NET Core MVC应用程序创建教程
- .NET Core中的File和PhysicalFile
- .NET Core 读取配置文件方法
- .NET Core 管道模型中间件及管道模拟实现
- ASP.NET Core多环境配置
- .NET Core 日志配置,NLog配置示例
- ASP.NET Core主机和应用启动流程
- .NET Core SkiaSharp替代System.Drawing的用法
- .NET Core 3.X路由中间件和终结点中间件
- .Net报错Could not find a part of the path bin\roslyn\csc.exe
- IIS中.NET Core报错HTTP Error 500.31 - ANCM Failed to Find Native Dependencies
- .NET Core分部视图PartialView用法
- .NET Core 视图组件Component用法
- ASP.NET Core的三种部署方式
- .NET Core中使用System.Drawing处理图像
- .NET Core Razor Page ajax请求返回400 Bad request
文章评论
评论问答