2013-12-19 29 views
8

我有一個ApiController的請求處理方法中此代碼:我是否需要從Request.CreateResponse()中處理HttpResponseException?

if (uri != null) 
{ 
    HttpResponseMessage r = Request.CreateResponse(HttpStatusCode.Redirect); 
    r.Headers.Location = uri; 
    throw new HttpResponseException(r); 
} 

的潛在問題是,「R」是從未配置(在我的代碼至少)。
我可以將其封裝在一個使用中,但在響應流式傳輸到客戶端之前不會「r」處理?

什麼是正確的操作方法是什麼?

+2

有趣的是,他們將組織他們班這種方式。我找不到任何有用的文檔,但你可以使用[這個構造函數](http://msdn.microsoft.com/en-us/library/hh835324(v = vs.118).aspx)一個狀態代碼呢? 「 –

+0

」不會過早處理?「準確地說,爲時過早? – spender

+2

@spender,我認爲OP會聲明它會在響應流式傳輸給客戶端之前處理掉。 –

回答

5

全部examples我已經看到表明你不必處置響應。

public Product GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
    var resp = new HttpResponseMessage(HttpStatusCode.NotFound) 
    { 
     Content = new StringContent(string.Format("No product with ID = {0}", id)), 
     ReasonPhrase = "Product ID Not Found" 
    } 
    throw new HttpResponseException(resp); 
    } 
    return item; 
} 

查看源代碼HttpResponseException,看來,它填充一個屬性(HttpResponseMessage Response)與價值和它的配置可能會導致HttpResponseMessage要麼引起的ObjectDisposedException或無法傳遞到客戶端。

您還會注意到,在源代碼中有一個SupressMessage:

[SuppressMessage("Microsoft.Reliability", 
    "CA2000:Dispose objects before losing scope", 
    Justification = "Instance is disposed elsewhere")] 

實例配置的其他地方(這是不是指HttpResponseMesssage,它不實現IDisposable)。

處理這個問題的正確方法是什麼?

我不相信您的代碼需要任何更改。

1

對我來說,「實例在別處處理」並不意味着你不需要處理它。

我的解決辦法是RegisterForDispose所以它變成了:

HttpResponseMessage r = Request.CreateResponse(HttpStatusCode.Redirect); 
r.Headers.Location = uri; 
this.request.RegisterForDispose(r); 
throw new HttpResponseException(r); 
相關問題