如何在ASP.NET Core的HTTP日志中忽略Swagger响应?
解决ASP.NET Web API中HTTP日志过滤Swagger内容的问题
方案一:通过HttpLoggingOptions路径过滤(简单直接)
在Program.cs配置HTTP日志时,利用RequestPathFilter排除Swagger相关路径,只记录业务接口的日志:
builder.Services.AddHttpLogging(options => { // 根据需求设置要记录的日志字段,示例为记录所有字段 options.LoggingFields = HttpLoggingFields.All; // 过滤Swagger相关路径,返回true则记录,false跳过 options.RequestPathFilter = path => { var isSwaggerPath = path.StartsWith("/swagger", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".json", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".html", StringComparison.OrdinalIgnoreCase); return !isSwaggerPath; }; });
该方法直接从路径层面过滤,不会影响Swagger的正常访问,仅跳过这些路径的HTTP日志记录。
方案二:自定义IHttpLoggingInterceptor(精细控制)
如果需要更灵活的控制(比如只过滤Swagger的响应日志,或针对特定请求方法过滤),可以实现自定义日志拦截器:
- 创建拦截器类:
public class SwaggerHttpLoggingInterceptor : IHttpLoggingInterceptor { public ValueTask OnRequestAsync(HttpLoggingInterceptorContext context) { // 判断是否为Swagger路径,是则禁止记录请求日志 if (IsSwaggerPath(context.HttpContext.Request.Path)) { context.SuppressLogging = true; } return ValueTask.CompletedTask; } public ValueTask OnResponseAsync(HttpLoggingInterceptorContext context) { // 单独控制响应日志,也可根据需求仅跳过响应日志 if (IsSwaggerPath(context.HttpContext.Request.Path)) { context.SuppressLogging = true; } return ValueTask.CompletedTask; } private bool IsSwaggerPath(PathString path) { return path.StartsWithSegments("/swagger", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".json", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".html", StringComparison.OrdinalIgnoreCase); } }
- 在
Program.cs中注册拦截器:
builder.Services.AddHttpLogging(options => { options.LoggingFields = HttpLoggingFields.All; }); // 注册自定义拦截器 builder.Services.AddSingleton<IHttpLoggingInterceptor, SwaggerHttpLoggingInterceptor>();
关于MediaTypeOptions未生效的说明
MediaTypeOptions用于指定哪些媒体类型的请求/响应会被记录,但Swagger的响应(如HTML、接口描述JSON)虽属于非application/json类型,但若你的API中还有其他同类型的业务请求需要记录,这种方式会误过滤。此外,Swagger请求可能携带其他媒体类型头,仅配置application/json会导致过滤不彻底,因此路径过滤是更精准的方案。
内容的提问来源于stack exchange,提问作者Mark Arrow
相关产品推荐
相关产品推荐

