【问题标题】:old response with DelegatingHandler, error 500DelegatingHandler 的旧响应,错误 500
【发布时间】:2013-12-12 10:45:19
【问题描述】:

我正在尝试将旧响应作为响应发回,但浏览器端出现错误 500 失败:

public class MyDelegatingHandler : DelegatingHandler
{
    [...]

    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        [...]
        // I basically tried:
        var response = oldResponse;
        // I also trying :
        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = oldResponse.Content
        };

        // response is sent back
        var tsc = new TaskCompletionSource<HttpResponseMessage>();
                tsc.SetResult(response);   
                return tsc.Task;
    }
}

我也尝试了这个基本示例:

var response = new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new StringContent("Hello")
};

这一次效果很好。

我的方法错了吗?我的代码有什么问题吗?

【问题讨论】:

    标签: asp.net http asp.net-web-api


    【解决方案1】:

    好的,我发现了问题:HttpResponseMessage 及其内容一旦被使用就被释放。这就是它不能被使用两次的原因。

    所以我尝试以这种方式重建 HttpResponseMessage:

    object contentValue = null;
    // Should be surrounded with if to check whether extraction succeded of course :-)
    cachedResponse.TryGetContentValue(out contentValue);
    var response = request.CreateResponse(contentValue);
    

    它似乎有效。

    感谢那些花时间阅读这篇文章的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多