2

I am getting the following error:

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.Net.Http.MultipartFormDataContent'. 

My code is this:

var content = new MultipartFormDataContent(); 

Then I add a few keys to the content.

After that I have a loop with this code inside:

using (var client = new HttpClient(handler, false)) { var response = client.PostAsync(uri, content).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content; bytes = responseContent.ReadAsByteArrayAsync().Result; } else { Response.End(); } } 

When it runs second time it gives me the above error.

Any idea why?

Thanks

Update. As suggested changing my code to this: I put this above the loop:

var client = new HttpClient(handler, false); using (client) { var response = client.PostAsync(uri, content).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content; bytes = responseContent.ReadAsByteArrayAsync().Result; } else { Response.End(); } } 

Now I am getting:

Cannot access a disposed object. Object name: 'System.Net.Http.HttpClient' 
14
  • Do you call Response.End(); that would prevent other stuff from running. Also MultipartFormDataContent is disposable, so don't dispose that. Might have to recreate that one as well. Commented Feb 7, 2022 at 11:50
  • The response will dispose the content when itself gets disposed. Don't reuse MultipartFormDataContent Commented Feb 7, 2022 at 11:51
  • @Ralf, what would I use? I am not too good with c#, just doing POC. Commented Feb 7, 2022 at 11:56
  • Actually i just tested this piece of code. Nothing inside this calls content.Dispose() and i was able to call it multiple times just fine. But you should also not recreate the HttpClient every time. Commented Feb 7, 2022 at 12:00
  • 1
    Don't use using (client) if you want to keep reusing the client. "using" will destroy the client at the end of the statement. If you also did using (content) then remove that using as well if you want to reuse the content. Commented Feb 7, 2022 at 12:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.