Web API Multipart表单数据:当新请求进入时,我可以将原始请求保存为文件吗?

时间:2013-06-14 19:19:41

标签: multipart asp.net-web-api

出于审计目的,我希望在处理新请求之前将原始请求(如Fiddler中所示)存储为文件。可以这样做,怎么做?谢谢!

1 个答案:

答案 0 :(得分:0)

是的,你可以做到。以下是我使用消息处理程序记录传入请求的示例。此处理程序可用于记录任何类型的请求(不仅是多部分请求)。

//add this handler in your config
config.MessageHandlers.Add(new LoggingMessageHandler());

// Logging message handler
public class LoggingMessageHandler : DelegatingHandler
{
    private StringBuilder messageBuilder = null;

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        messageBuilder = new StringBuilder();

        messageBuilder.AppendFormat("{0} {1}", request.Method.Method, request.RequestUri);
        messageBuilder.AppendLine();

        //get request headers information
        GetHeaders(request.Headers);

        //get request content's headers and body
        if (request.Content != null)
        {
            GetHeaders(request.Content.Headers);

            // NOTE 1: 
            // ReadAsStringAsync call buffers the entire request in memory.
            // So, even though you could be consuming the request's stream here, since the entire request is buffered
            // in memory, you can expect the rest of the call stack to work as expected.
            // NOTE 2:
            // Look for performance considerations when the request size is too huge.
            string body = await request.Content.ReadAsStringAsync();

            messageBuilder.AppendLine();
            messageBuilder.Append(body);
        }

        //TODO: log the message here
        //logger.Log(messageBuilder.ToString())

        // call the rest of the stack as usual
        return await base.SendAsync(request, cancellationToken);
    }

    private void GetHeaders(HttpHeaders headers)
    {
        foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
        {
            messageBuilder.AppendLine(string.Format("{0}: {1}", header.Key, string.Join(",", header.Value)));
        }
    }
}