When or if to Dispose HttpResponseMessage when calling ReadAsStreamAsync?

When or if to Dispose HttpResponseMessage when calling ReadAsStreamAsync?

By : user2955897
Date : November 22 2020, 10:48 AM
wish of those help
So it seems like the calling code needs to know about and take ownership of the response message as well as the stream, or I leave the response message undisposed and let the finalizer deal with it. Neither option feels right.
code :

Share : facebook icon twitter icon
HttpClient: limit response (downloaded file) size while using HttpResponseMessage.Content.ReadAsStreamAsync()

HttpClient: limit response (downloaded file) size while using HttpResponseMessage.Content.ReadAsStreamAsync()

By : mianliu
Date : March 29 2020, 07:55 AM
it helps some times If Richard's answer doesn't help because the content is chunked then you should look into the ProgressMessageHandler that is part of the WebAPI.Client nuget that receives events periodically and allows you to monitor the bytes transferred. Using this event handler you could cancel the operation if the bytes transferred exceeds a certain amount.
How do I Dispose a HttpResponseMessage in my Web Api Method?

How do I Dispose a HttpResponseMessage in my Web Api Method?

By : albe
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Exception about accessing a disposed object is obvious because when execution leaves the using block, response is disposed, but you're returning it out of the using block and out of the method. You can't access that object outside of the method, because it simply doesn't exist anymore.
In general, to solve the CA2000 warning simply dispose the instance of HttpResponseMessage class explicitly when you don't need it anymore.
Not calling Dispose on HttpRequestMessage and HttpResponseMessage in asp.net core

Not calling Dispose on HttpRequestMessage and HttpResponseMessage in asp.net core

By : multidog888
Date : March 29 2020, 07:55 AM
will help you I opened an issue on the github repository where the code examples belong to.
When to dispose of a HttpResponseMessage or a HttpContent

When to dispose of a HttpResponseMessage or a HttpContent

By : OmarC
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Don't use using blocks. Just store them in a private variable and dispose of them with the controller disposal. Also, you can use Task.FromResult for already completed tasks.
code :
private StringContent _httpContent
private CustomHttpResponse _customHttpResponse

public async Task<IHttpActionResult> PostOrganizationAsync(Organization organization)
    using (var context = new ContextHandler())
        bool added = await context.AddOrganizationAsync(organization);
        if (added)
            return Ok();
            this._httpContent = new StringContent("An organization with this Id already exists on the database"))
            this._customHttpResponse = new CustomHttpResponse(HttpStatusCode.Conflict, httpContent);
            return this._customHttpResponse;

protected override void Dispose(bool disposing)
    if (disposing)
        if (this._httpContent != null)
        if (this._customHttpResponse != null)
public class CustomHttpResponse : IHttpActionResult
    public HttpStatusCode StatusCode;
    public HttpContent Content;

    public CustomHttpResponse(HttpStatusCode httpStatusCode, HttpContent httpContent)
        StatusCode = httpStatusCode;
        Content = httpContent;

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        HttpResponseMessage httpResponse = new HttpResponseMessage(StatusCode);
        httpResponse.Content = Content;
        return Task.FromResult(httpResponse);
HttpResponseMessage do you dispose it?

HttpResponseMessage do you dispose it?

By : Pat Morrissey
Date : March 29 2020, 07:55 AM
it fixes the issue Whilst waiting for the new shiny HttpClientFactory addressing all the issues of HttpClient, ,
Do you use a Using statement with HttpResponseMessage?
Related Posts Related Posts :
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • Check what needs full trust
  • What is the execution order of an MVC Razor view/layout
  • Table designer (Entity Framework) is too resource intense
  • How to clean up an exception string so it can be displayed via Javascript Alert?
  • Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)
  • C# api responce and request
  • Dynamodb putitem function not working properly
  • theme in windows phone(light or dark) using c#
  • Backup attached database file(.mdf) using c# and SQL Server
  • What is 'TextFile' and where it is uses in WPF project
  • Using same alias for multiple namespaces
  • how to move mails into separate folders
  • Multithreaded Uploader
  • Memory fragmentation?
  • C# correct exception handling
  • "Could not open macro storage" when accessing using file on another machine
  • How to access other directories of hosted server
  • C# Jagged Array check if value exists/true
  • Why can't I type Clone() properly?
  • exception on accessing dictionary from list
  • Getting the immediate response from server without waiting to 200 message
  • Why am I getting exception Directory Is Not empty?
  • Could not load file or assembly 'CefSharp.dll' or one of its dependencies
  • Sending Email By Using C# in unity3D?
  • Correct usage of await async in webapi
  • Program update code issue
  • Marshal.Copy attempted to read or write protected memory At Random Times
  • Restrict Type variable to specific class or subclass
  • Horizontal text alignment in a PdfPCell
  • C# crashing with Form.show() command, ObjectDisposedException - Deeper look / explanation please
  • Will the result of a LINQ query always be guaranteed to be in the correct order?
  • "Could not find default endpoint element that references contract"
  • Umbraco Request.QueryString is null if it's the first time the page is loaded
  • Error inconsistent accessibility method C#
  • How to program Intel Xeon Phi with C#?
  • remove nested element using regular expression
  • Is there a C# alternative to Java's vararg parameters?
  • Clear particular column values in DataTable
  • how to add event handler to programatically created checkboxes
  • Cannot apply indexing with [] to an expression of type 'System.Collections.Specialized.NameValueCollection'
  • Check for key in pre-existing dictionary in case insensitive manner
  • How to remove year from datetime object?
  • Accessing Settings in different ways
  • "This project is empty" error in Sonarqube
  • How to create reusable icon menu in Xamarin
  • Value Cannot be null in Ado.Net connectivity
  • Adding a custom/dynamic attribute when using XSD.exe
  • How to convert object to correct type
  • Automatically sign out from Forms Authentication in ASP.NET when browser is closed
  • Can a WCF service support both Buffered and Streamed transfer modes?
  • Verify a CA Certificate with a public key in C#
  • How to invoke a Web Service that requires the "patch" verb using the C# WebClient wrapper?
  • Proper way a implementing property based on generic type
  • Closing a form that is created in another thread
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org