2015-03-19 84 views
1

我的ASP.NET Web API應用程序需要充當客戶端與另一個HTTP資源之間的中間層。從後端HTTP服務獲取的響應需要通過一些基本驗證 - 但最終響應需要與後端調用相同。編制Web API中的HttpResponseMessage

這是我在做這個使用Web API的嘗試:

[HttpGet] 
public async Task<HttpResponseMessage> GetSearchResults() 
{   

    var client = new HttpClient(); 
    var backendResponse = await client.GetAsync("http://api.duckduckgo.com/?q=DuckDuckGo&format=json"); 

    ValidateResponseStream(await backendResponse.Content.ReadAsStreamAsync()); 

    var myResponse = new HttpResponseMessage(HttpStatusCode.OK); 
    myResponse.Content = backendResponse.Content; 

    return myResponse; 
} 

雖然這按預期工作,我認爲這是不正確,因爲我不處置backendResponse

在不需要先將後端響應流複製到MemoryStream的情況下處理backendResponse的好方法是什麼?

編輯:我發現this discussion thread其中明確指出處置一個HttpResponseMessage是必需的;我仍然不清楚這是否會在上述通話中自動發生。我還想明確地說明Dispose被調用。

回答

0

如果您已經擁有了backendResponse所需的內容,您能否在返回myResponse之前調用backendResponse.Dispose()?

1

自己處理對象總是很聰明的。您應該將使用對象包裝在使用說明中,如下所示:

HttpResponseMessage myResponse; 

using (var client = new HttpClient()) 
using(var backendResponse = await client.GetAsync("http://api.duckduckgo.com/?q=DuckDuckGo&format=json")) 
{ 
    ValidateResponseStream(await backendResponse.Content.ReadAsStreamAsync()); 
    myResponse = new HttpResponseMessage(HttpStatusCode.OK); 
    myResponse.Content = backendResponse.Content; 
} 

return myResponse; 

這樣可以確保一切都處置完畢。

此外,我認爲如果您想要處置,您需要製作副本。

相關問題