简体   繁体   English

如何正确处理从 controller 返回的 HttpResponseMessage?

[英]How to properly dispose HttpResponseMessage returned from a controller?

I have an action that returns an HttpResponseMessage .我有一个返回HttpResponseMessage的操作。

How do I dispose such an object?我该如何处置这样的 object? After I return it, I can't really dispose it.退回后,我真的无法处理它。

Example:例子:

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

My Action:我的行动:

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

It's weird because on other parts of my code no such warning exists.这很奇怪,因为在我的代码的其他部分不存在这样的警告。 Is the function confusing my IntelliSense ? function 是否让我的IntelliSense感到困惑?
The action is not invoked from anywhere else.该操作不会从其他任何地方调用。
It returns its result to its endpoint.它将结果返回到其端点。

After researching, the best practice according to this article is to dispose it.经过研究,根据本文的最佳做法是处置它。

It states that:它指出:

The safest, general advice would be to always dispose of the HttpResponseMessage once you have finished with using it.最安全、最通用的建议是在使用完 HttpResponseMessage 后始终将其丢弃。 This does lead to a little more code noise but ensures that regardless of the internals and any future changes, your code will free/clean up unused resources such as connections as quickly as possible.这确实会导致更多的代码噪音,但可以确保无论内部结构和未来的任何更改如何,您的代码都会尽快释放/清理未使用的资源,例如连接。 Be aware that once you dispose of the content, it will become unusable for anyone else who has been passed a reference to it.请注意,一旦您处理了该内容,它将变得无法被其他任何通过引用它的人使用。

The article provides this example on how to properly use the HttpResponseMessage and then dispose of it本文提供了这个示例,说明如何正确使用 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; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM