c# - 如何在多部分/表单数据请求的请求正文中记录文件内容

标签 c# asp.net asp.net-mvc asp.net-web-api logging

我正在尝试将我的 asp.net Web API 项目中的所有请求记录到文本文件中。我正在使用 DelegationHandler 功能在我的应用程序中实现日志记录机制,下面是代码片段,

public class MyAPILogHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
           // Captures all properties from the request.
            var apiLogEntry = CreateApiLogEntryWithRequestData(request);
            if (request.Content != null)
            {
                    await request.Content.ReadAsStringAsync()
                        .ContinueWith(task =>
                        {
                            apiLogEntry.RequestContentBody = task.Result;
                        }, cancellationToken);
            }

            return await base.SendAsync(request, cancellationToken)
                .ContinueWith(task =>
                {
                    var response = task.Result;

                    // Update the API log entry with response info
                    apiLogEntry.ResponseStatusCode = (int)response.StatusCode;
                    apiLogEntry.ResponseTimestamp = DateTime.Now;

                    if (response.Content != null)
                    {
                        apiLogEntry.ResponseContentBody = response.Content.ReadAsStringAsync().Result;
                        apiLogEntry.ResponseContentType = response.Content.Headers.ContentType.MediaType;
                        apiLogEntry.ResponseHeaders = SerializeHeaders(response.Content.Headers);
                    }   

                    var logger = new LogManager();
                    logger.Log(new LogMessage()
                    {
                       Message = PrepareLogMessage(apiLogEntry),
                       LogTo = LogSource.File
                    });

                    return response;
                }, cancellationToken);
        }
}

上述实现按预期工作,并将所有必需的请求/响应信息记录到文件中。

但是,当我们进行任何带有附加图像的 multipart/form-data POST api 调用时,在记录此请求后,日志文件会变得巨大,因为所有图像/二进制内容都被转换为字符串并将其写入文本文件。请查找以下日志文​​件内容,

Body: 
----------------------------079603462429865781513947
Content-Disposition: form-data; name="batchid"

22649EEE-3994-4225-AF73-D9A6B659CAE3
----------------------------079603462429865781513947
Content-Disposition: form-data; name="files"; filename="d.png"
Content-Type: image/png

PNG


IHDR    í   %v ¸   sRGB ®Îé   gAMA  ±üa      pHYs  à  ÃÇo¨d  ÿ¥IDATx^ìýX]K¶(
·îsß»ß÷þï{O÷iÛ    Á2âîîîÁe¹âîî,<@   Á$÷w_ÈZó5$Dwvv×}
----------------------------4334344396037865656556781513947
Content-Disposition: form-data; name="files"; filename="m.png"
Content-Type: image/png

PNG


IHDR    í   %v ¸   sRGB ®Îé   gAMA  ±üa      pHYs  à  ÃÇo¨d  ÿ¥IDATx^ìýX]K¶(
·îsß»ß÷þï{O÷iÛ    Á2âîîîÁe¹âîî,<@   Á$÷w_ÈZó5$Dwvv×}

我不想记录请求正文的二进制内容,仅记录请求正文文件内容就足够了,例如,

    ----------------------------079603462429865781513947
    Content-Disposition: form-data; name="batchid"

    22649EEE-3994-4225-AF73-D9A6B659CAE3
    ----------------------------079603462429865781513947
    Content-Disposition: form-data; name="files"; filename="d.png"
    Content-Type: image/png

    ----------------------------4334344396037865656556781513947
    Content-Disposition: form-data; name="files"; filename="m.png"
    Content-Type: image/png

您能否建议如何防止记录请求正文的二进制内容并仅记录请求正文的文件内容。

最佳答案

据我所知,您正在实现类似于 this 的内容方法。 上传文件时(即请求类型“multipart/form-data”),其实际内容始终以“Content-Type:{ContentTypeValue}\r\n\r\”开头。 n"序列,下一个 header 以 "\r\n--" 序列开头(如日志中所示)。您可以在 ReferenceSource 探索有关原始请求数据解析的更多信息。 。因此,您可以删除有关文件的所有内容(如果存在),例如通过正则表达式:

内容类型:{ContentTypeOrOctetStream}\r\n\r\n{FileContentBytesToRemove}\r\n

using System.Text.RegularExpressions;
...
string StripRawFileContentIfExists(string input) {
    if(input.IndexOf("Content-Type") == -1)
        return input;
    string regExPattern = "(?<ContentTypeGroup>Content-Type: .*?\\r\\n\\r\\n)(?<FileRawContentGroup>.*?)(?<NextHeaderBeginGroup>\\r\\n--)";
    return Regex.Replace(input, regExPattern, me => me.Groups["ContentTypeGroup"].Value + string.Empty + me.Groups["NextHeaderBeginGroup"].Value);
}
...
//apiLogEntry.RequestContentBody = task.Result;
apiLogEntry.RequestContentBody = StripRawFileContentIfExists(task.Result);

关于c# - 如何在多部分/表单数据请求的请求正文中记录文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033995/

相关文章:

asp.net-mvc - ASP.NET MVC : Stack overflow error when calling Html. 渲染部分()

javascript - 事件触发时来自 Controller 的 SignalR 消息可查看

c# - 如何在 ASP.NET 身份框架中刷新当前经过身份验证的用户的角色更改成员身份?

c# - 是否存在使用不会处理对象的情况?

c# - 如何将 Bool (BIT) 参数传递给 SQL Server?

c# - 使用带有动态加载 DLL 的 CaSTLe Windsor 解析 Controller

c# - 复杂 - 在 Powershell c# 中用 Regex 替换

c# - 结合表单例份验证(授权)和基本身份验证(消息处理程序)的安全 Web API

html - td 数据不是单行输入

asp.net - 在服务器上上传时 Asp.net mvc-5 应用程序中的 MethodAccessException