0

出于审计目的,我想在处理原始请求(如 Fiddler 中显示的那样)存储新请求时将其存储为文件。这可以做到吗?怎么做?谢谢!

4

1 回答 1

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)));
        }
    }
}
于 2013-06-15T21:30:14.437 回答