【问题标题】:ignore HttpRequest Field for StreamReader忽略 StreamReader 的 HttpRequest 字段
【发布时间】: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


【解决方案1】:

我无法完全按照我的意愿解决问题。 但是通过完全删除 Body 信息解决了问题:)

            var formattedRequest = $"{request.Scheme} {request.Host}{request.Path} {request.QueryString}";

【讨论】:

    猜你喜欢
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2015-12-01
    • 2019-12-31
    相关资源
    最近更新 更多