【发布时间】:2018-06-10 13:36:22
【问题描述】:
我正在尝试将我的 asp.net Web API 项目中的所有请求记录到一个文本文件中。我正在使用DelegationHandler 功能在我的应用程序中实现日志记录机制,下面是代码sn-p,
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
您能否建议如何防止记录请求正文的二进制内容并仅记录请求正文的文件内容。
【问题讨论】:
-
我用一个简单的例子更新了我现有的答案。
标签: c# asp.net asp.net-mvc asp.net-web-api logging