【问题标题】:.NET Web Api Logging Response Body.NET Web Api 日志记录响应正文
【发布时间】:2014-10-27 13:12:58
【问题描述】:

我正在尝试使用 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 文档带有 Server cannot append header after HTTP headers have been sent 消息。

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

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

【问题讨论】:

    标签: asp.net-web-api


    【解决方案1】:

    尝试将处理程序更改为使用 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);
            }
        }       
    

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

    【讨论】:

    • 我修改了处理程序以使用上面的 async/await 代码,但我仍然收到同样的错误。
    • 只需添加此处理程序,即可在新的 Web API 项目上轻松复制该错误。
    • 嗯,我无法重现该问题。代码是否仍然在await response.Content.ReadAsStringAsync(); 处抛出异常?
    猜你喜欢
    • 2014-08-10
    • 2010-09-13
    • 1970-01-01
    • 2014-11-17
    • 2018-12-20
    • 2013-11-13
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    相关资源
    最近更新 更多