我在 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/