我是否需要从Request.CreateResponse()处理HttpResponseException?

我在ApiController的请求处理方法中有这个代码:

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

潜在的问题是“r”从未处理过(至少在我的代码中)。
我可以将它包装在一个使用中,但是在响应流式传输到客户端之前不会“r”处理掉?

处理这个问题的正确方法是什么?

我见过的所有例子都表明你不必处理响应。

 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的源代码,看起来它使用该值填充Property( HttpResponseMessage Response )并处理它可能会导致HttpResponseMessage导致ObjectDisposedException或无法传递给客户端。

您还会注意到源代码中有一个SupressMessage:

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

实例在其他地方处理(这不是指HttpResponseMesssage,它不实现IDisposable)。

处理这个问题的正确方法是什么?

我不认为您的代码需要进行任何更改。

对我来说,“实例被置于别处”并不意味着你不需要处理它。

我的解决方案是RegisterForDispose因此它变为:

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