在 action 方法中抛出 HttpResponseException 时处理

我的问题的来源是以下代码,它是Microsoft 文档中包含的代码片段的一部分,用于在 asp.net web api 中进行异常处理:


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

无论HttpResponseMessage和StringContent实现IDisposable接口,但没有人在上面的代码中调用方法IDisposable.Dispose。

这是一个问题吗?不处理这些对象是否有任何副作用?


根据这篇文章,一个可能的解决方案可能是将上面的代码更改为以下内容:


var content = new StringContent(string.Format("No product with ID = {0}", id));

var resp = new HttpResponseMessage(HttpStatusCode.NotFound)

{

    Content = content,

    ReasonPhrase = "Product ID Not Found"

};


this.Request.RegisterForDispose(content);

this.Request.RegisterForDispose(resp);


throw new HttpResponseException(resp);

这真的有必要,还是有可能避免这种情况(根据 Microsoft 文档中显示的内容)?


跃然一笑
浏览 116回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP