2013-12-12 43 views
0

我想回送一個應答的舊響應,這將失敗,並錯誤500瀏覽器端:舊響應與DelegatingHandler,錯誤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") 
}; 

這一次,它工作得很好。

我的方法錯了嗎?我的代碼中是否有簡單的錯誤?

回答

0

好吧,我發現了問題:一旦它已被消耗的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); 

,它似乎工作。

感謝那些誰花時間閱讀帖子。