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'
Response.End();that would prevent other stuff from running. AlsoMultipartFormDataContentis disposable, so don't dispose that. Might have to recreate that one as well.content.Dispose()and i was able to call it multiple times just fine. But you should also not recreate the HttpClient every time.using (client)if you want to keep reusing the client. "using" will destroy the client at the end of the statement. If you also didusing (content)then remove that using as well if you want to reuse the content.