【问题标题】:How to properly dispose HttpResponseMessage returned from a controller?如何正确处理从控制器返回的 HttpResponseMessage?
【发布时间】:2020-02-25 20:22:44
【问题描述】:

我有一个返回 HttpResponseMessage 的操作。

如何处置这样的对象?退货后,我真的不能处理了。

示例:

 return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
 // Inside function SomeMethod

我的行动:

 public HttpResponseMessage SomeAction()
 {
    return SomeMethod(); // Warning that this is not disposed
 }

这很奇怪,因为在我的代码的其他部分不存在这样的警告。该功能是否使我的 IntelliSense 感到困惑?
该操作不会从其他任何地方调用。
它将结果返回到它的端点。

【问题讨论】:

  • 在它被返回并且没有被引用之后,它应该已经被处理/标记为收集,对吧?
  • @ZacharyBrooks - 有一个显式的 Dispose,来自 HttpResponseMessage 实现的 IDisposable 接口。
  • @SpiritBob - 你会在消费者端处理它 - 或者我错过了什么。
  • @Rakesh 不,我会提供一个例子。

标签: c# asp.net


【解决方案1】:

经过研究,根据this文章的最佳做法是处置它。

它指出:

最安全的一般建议是,在您使用完 HttpResponseMessage 后始终将其丢弃。这确实会导致更多的代码噪音,但确保无论内部结构和任何未来更改如何,您的代码都会尽快释放/清理未使用的资源,例如连接。请注意,一旦您处置了该内容,它就会变得无法供其他任何通过引用传递的人使用。

本文提供了如何正确使用HttpResponseMessage然后将其丢弃的示例

public async Task<SomeData> GetSomeDataAsync(Uri uri)
{

    HttpResponseMessage response = await _httpClient.GetAsync(uri);
    SomeData result = null; 

    try
    {
        // In this case we'll expect our caller to handle a HttpRequestException
        // if this request was not successful.
        response.EnsureSuccessStatusCode();

        result = await response.Content?.ReadAsAsync<SomeData>();
    }
    finally
    {
        // Dispose of HttpResponseMessage to ensure we free up system resources 
        // and release the network connection (if that hasn't already happened).
        // Not required in a majority of common cases but always safe to do as long
       // as you have not passed the content onto other threads / consumers.
        response.Dispose(); 
    }

    // Either return the result or in this case a daft 
    // default value. It's okay for this example!
    return result ?? SomeData.Empty; 
}

【讨论】:

  • 你看到我的例子了吗?我无法实现您向我展示的内容,因为要处理它,我必须回到上下文中,这是不可能的。
  • 这不是最佳做法。实现 IDisposable 的类的最佳实践是使用 using。只有当using 不可用时,您才会直接调用 Dispose,例如当声明和一次性在不同的方法/范围内时。
  • @SpiritBob 答案,如我的示例中所示,说明您应该返回内容而不是对象,以便您可以处理响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多