.NET Web Api日志记录响应正文

时间:2014-10-27 13:12:59

标签: asp.net-web-api

我正在尝试使用DelegatingHandler记录Web Api响应主体。

    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        return base.SendAsync(request, cancellationToken).ContinueWith(task =>
        {
            var response = task.Result;
            LogResponseLoggingInfo(response);
            return response;
        });
    }

    private void LogResponseLoggingInfo(HttpResponseMessage response)
    {
        string responseBody = string.Empty;

        if (response.Content != null)
        {
            responseBody = response.Content.ReadAsStringAsync().Result;
            //WriteToLogFile(responseBody);
        }
    }

只要对Web Api的调用返回响应,它就可以正常工作.StatusCode等于HttpStatusCode.OK。

但是,任何返回任何其他StatusCode的调用(例如Unauthorized)都会导致正确的响应401仅在每次其他调用时正确返回。

其他时候,我收到500响应,内部服务器错误。

使用Fiddler查看500个错误的原始响应,显示HTML文档,服务器无法在发送HTTP标头消息后附加标头。

如果我注释掉 responseBody = response.Content.ReadAsStringAsync()。Result; 行,则每次都会成功返回正确的401错误响应。

有人知道导致错误的原因以及解决方法吗?

1 个答案:

答案 0 :(得分:0)

尝试更改处理程序以使用async / await:

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,       System.Threading.CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        await LogResponseLoggingInfo(response);

        return response;
    }

    private async Task LogResponseLoggingInfo(HttpResponseMessage response)
    {
        string responseBody = string.Empty;

        if (response.Content != null)
        {
            responseBody = await response.Content.ReadAsStringAsync();
            //WriteToLogFile(responseBody);
        }
    }       

如果您使用async / await,请远离使用.ContinueWith和.Result,因为您不需要它。以下是一些信息:http://www.journeyofcode.com/will-block-debunking-asyncawait-pitfalls/http://code.jonwagner.com/2012/09/06/best-practices-for-c-asyncawait/