【发布时间】:2021-06-11 06:20:21
【问题描述】:
我想忽略 StreamReader.ReadToEndAsync() 的 HttpRequest 中的某些字段 因为如果我不能阻止它会抛出一个大日志
例如: 我的控制器
[HttpPost, DisableRequestSizeLimit]
public async Task<IActionResult> UploadFile([FromForm] MyModel ysisFile)
{
//bla bla
}
我的请求模型
public class MyModel
{
public string DocumentId { get; set; }
public string DocumentType { get; set; }
// i want to ignore this property
public IFormFile File { get; set; }
}
我的日志格式化器
private async Task<string> FormatRequest(HttpRequest request)
{
// Leave the body open so the next middleware can read it.
using var reader = new StreamReader(
request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
leaveOpen: true);
var body = await reader.ReadToEndAsync();
// Do some processing with body…
var formattedRequest = $"{request.Scheme} {request.Host}{request.Path} {request.QueryString} {body}";
// Reset the request body stream position so the next middleware can read it
request.Body.Position = 0;
return formattedRequest;
}
【问题讨论】:
-
这可能无法如您所愿?那个主体流只是一堆数据,在我们开始谈论任何类型的字段或属性之前。但是,如果您使用操作过滤器进行日志记录,则可以依赖已经绑定的模型,而不必读取流。
标签: c# .net asp.net-core logging .net-core