ASP.NET Core 8如何针对特定路径排除HTTP请求体日志?
如何针对特定请求路径自定义HttpRequestLogging的日志字段?
可以实现这个需求,你可以通过自定义HttpLoggingInterceptor来根据请求路径动态调整日志字段的配置。具体实现方式如下:
- 实现
IHttpLoggingInterceptor接口,在OnLoggingFieldsSelection方法中判断请求路径,匹配到目标路径时修改日志字段配置 - 将自定义拦截器注册到HttpLogging的配置体系中
代码实现示例
首先创建自定义拦截器类:
public class PathBasedHttpLoggingInterceptor : IHttpLoggingInterceptor { public ValueTask OnLoggingFieldsSelection(HttpLoggingFieldsSelectionContext context) { // 检查当前请求路径是否包含目标字符串 if (context.HttpContext.Request.Path.Value?.Contains("/myspecial/request/notToLog") == true) { // 切换为不记录请求体的日志字段配置 context.LoggingFields = HttpLoggingFields.RequestProperties | HttpLoggingFields.ResponsePropertiesAndHeaders; } // 非目标路径保持原有配置 return ValueTask.CompletedTask; } }
然后修改服务注册代码,添加自定义拦截器:
builder.Services.AddHttpLogging(loggingOptions => { loggingOptions.LoggingFields = HttpLoggingFields.Request | HttpLoggingFields.Response; // 注册自定义路径拦截器 loggingOptions.Interceptors.Add<PathBasedHttpLoggingInterceptor>(); });
配置完成后,当请求路径包含/myspecial/request/notToLog时,日志字段会自动切换为你需要的配置(不记录请求体);其他请求则保持初始的完整日志字段配置。
内容的提问来源于stack exchange,提问作者silent
相关产品推荐
相关产品推荐

