c# - 我是否需要处理来自 Request.CreateResponse() 的 HttpResponseException?

标签 c# asp.net dispose

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

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

潜在的问题是“r”永远不会被释放(至少在我的代码中是这样)。
我可以将它包装在一个 using 中,但是在将响应流式传输到客户端之前,“r”不会被处理掉吗?

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

最佳答案

所有 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)。

What is the correct way to handle this?

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

关于c# - 我是否需要处理来自 Request.CreateResponse() 的 HttpResponseException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20688999/

相关文章:

c# - 从 xdocument C# 获取字典

c# - 有没有更好的方法来处理两个 bool 条件的组合?

瀑布对话框内的 C# bot V4 文本提示

c# - 将异步结果生成给 ASP PartialView

vb.net - .dispose() 方法有什么作用吗?

.net - IDisposable 接口(interface)如何工作?

.net - .Net 中的 Marshal.DestroyStructure 与 Marshal.FreeHGlobal

c# - MEF 对象生命周期

c# - 使用 Twitterizer 发布推​​文

c# - ASP.NET 登录状态 : logout not working