简体   繁体   中英

How to properly dispose HttpResponseMessage returned from a controller?

I have an action that returns an HttpResponseMessage .

How do I dispose such an 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 ?
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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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