System.Net.Http
HttpResponseMessage

HttpResponseMessage.Content.Dispose()

public void Content.Dispose()

Releases the unmanaged resources used by the Content property and optionally releases the managed resources.

This method is called automatically when the HttpResponseMessage itself is disposed of, if the Content is not null.

Remarks

The Content property is an HttpContent object, which implements the IDisposable interface. This means that the underlying stream and network resources associated with the response body need to be explicitly released to prevent resource leaks.

Calling Dispose() on the HttpResponseMessage will also dispose of its Content property if it has been set.

It is recommended to always dispose of HttpResponseMessage objects when they are no longer needed, typically using a using statement in C# or `try-finally` block.

Example Usage

```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class HttpClientExample { public static async Task MakeRequestAndProcessResponse() { using (HttpClient client = new HttpClient()) { try { HttpResponseMessage response = await client.GetAsync("https://www.example.com"); // Ensure the response content is disposed of using (HttpContent content = response.Content) { if (content != null) { string responseBody = await content.ReadAsStringAsync(); Console.WriteLine("Response Body:"); Console.WriteLine(responseBody); // content.Dispose() is called automatically here by the 'using' statement } } // response.Dispose() is called automatically here by the outer 'using' statement } catch (HttpRequestException e) { Console.WriteLine("\nException Caught!"); Console.WriteLine("Message :{0} ", e.Message); } } } } ```

Returns

void

Exceptions

  • ObjectDisposedException: The HttpResponseMessage has already been disposed.
Documentation last updated: 2023-10-27