我是否需要从 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 的源代码,似乎它使用该值填充属性 (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);

最新更新