我需要从Request.CreateResponse处置的Htt的presponseException()? [英] Do I need to dispose an HttpResponseException from Request.CreateResponse()?

查看:554
本文介绍了我需要从Request.CreateResponse处置的Htt的presponseException()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ApiController的请求处理方法中使用这个code:

I have this code within a request handling method of an ApiController:

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

潜在的问题是,R是永远不会处理(在我的code。至少)。结果
响应被传输到客户端之前使用,我可以在包装这一点,但以后就不会R得到处置?

The potential problem is that "r" is never disposed (in my code at least).
I could wrap this in a using, but then wouldn't "r" get disposed before the response is streamed to the client?

什么是正确的操作方法是什么?

What is the correct way to handle this?

推荐答案

所有的<一个href=\"http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling\">examples我见过表明你没有处置响应。

All the examples I've seen show that you do not have to dispose of the Response.

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;
}

在源$ C ​​$ C展望<一个href=\"http://aspnetwebstack.$c$cplex.com/SourceControl/latest#src/System.Web.Http/Htt$p$psponseException.cs\">Htt$p$psponseException,看来,它填充一个属性(的Htt presponseMessage响应)与价值和它的处理可能会造成的Htt presponseMessage要么造成的ObjectDisposedException或失败被传递到客户端。

Looking at the source code to HttpResponseException, it appears that it populates a Property (HttpResponseMessage Response) with that value and disposing of it would probably cause the HttpResponseMessage either cause an ObjectDisposedException or fail to be delivered to the client.

您还会注意到,在源$ C ​​$ C有一个苏pressMessage:

You'll also notice that in the source code there is a SupressMessage:

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

实例配置的其他地方(这是不是指的Htt presponseMesssage,它没有实现IDisposable)。

Instance is disposed of elsewhere (this is not referring to HttpResponseMesssage, it does not implement IDisposable).

什么是正确的操作方法是什么?

What is the correct way to handle this?

我不相信任何更改您的code是必需的。

I don't believe any change to your code is required.

这篇关于我需要从Request.CreateResponse处置的Htt的presponseException()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆