After the first request HttpClientHandler

I want to send two requests from my ViewModel (first GET and then POST) using HttpClient. The GET request completes without errors. But if then I send a POST request, I got an exception:

{System.ObjectDisposedException: The object has been closed. (Exception from HRESULT: 0x80000013)}  System.Exception {System.ObjectDisposedException}

      

Or if I made a POST request before the GET-POST completes ok and the GET fails with the same exception.

I am using one HttpClientHandler for both requests (because I store cookies in this HttpClientHandler)

public async Task<CategoryGroupModel> GetCategoryGroup(int categoryGroupId)
{
  var handler = new HttpClientHandler {CookieContainer = App.Cookies};

  using (var client = new MmcHttpClient(handler))
  {
    // HTTP GET
    HttpResponseMessage response = await client.GetAsync("api/categorygroups/" + categoryGroupId);
    if (response.IsSuccessStatusCode)
    {
      var resultAsString = await response.Content.ReadAsStringAsync();
      var jsonResult = JObject.Parse(resultAsString);
      var wsResponse = jsonResult.ToObject<WebServiceResponse<CategoryGroupModel>>();

      if (wsResponse.Status == HttpStatusCode.OK)
      {
        return wsResponse.Result;
      }
      else
      {
        throw new Exception();
      }
    }
    else
    {
      throw new Exception();
    }
  }
}

public async Task<CategoryGroupModel> CreateCategoryGroup(CategoryGroupModel categoryGroup)
{
  var handler = new HttpClientHandler {CookieContainer = App.Cookies};

  using (var client = new MmcHttpClient(handler))
  {
    var response = await client.PostAsJsonAsync("api/categorygroups", categoryGroup);
    if (response.IsSuccessStatusCode)
    {
      var resultAsString = await response.Content.ReadAsStringAsync();
      var jsonResult = JObject.Parse(resultAsString);
      var wsResponse = jsonResult.ToObject<WebServiceResponse<CategoryGroupModel>>();

      if (wsResponse.Status == HttpStatusCode.OK)
      {
        return wsResponse.Result;
      }
      else
      {
        throw new Exception();
      }
    }
    else
    {
      throw new Exception();
    }
  }
}

      

MmcHttpClient:

public class MmcHttpClient : HttpClient
{
  public MmcHttpClient(HttpClientHandler handler) : base(App.Handler)
  {
    BaseAddress = new Uri("http://localhost:65066/");
    DefaultRequestHeaders.Accept.Clear();
    DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  }
}

      

StackTrace:

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.Net.Http.HttpClientHandler'.
at System.Net.Http.HttpClientHandler.CheckDisposed()
at System.Net.Http.HttpClientHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.PostAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.PostAsync(String requestUri, HttpContent content, CancellationToken cancellationToken)
at System.Net.Http.HttpClientExtensions.PostAsync[T](HttpClient client, String requestUri, T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, CancellationToken cancellationToken)
at System.Net.Http.HttpClientExtensions.PostAsync[T](HttpClient client, String requestUri, T value, MediaTypeFormatter formatter, CancellationToken cancellationToken)
at System.Net.Http.HttpClientExtensions.PostAsJsonAsync[T](HttpClient client, String requestUri, T value, CancellationToken cancellationToken)
at System.Net.Http.HttpClientExtensions.PostAsJsonAsync[T](HttpClient client, String requestUri, T value)
at MMCClient.Repositories.CategoryGroupRepository.<CreateCategoryGroup>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at MMCClient.ViewModels.CategoryGroupViewModel.<Create>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__3(Object state)
at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()}   System.Exception {System.ObjectDisposedException}

      

+3


source to share


1 answer


That was my fault. After adding the second parameter (disposeHandler) to the HttpClient constructor, everything works well:

public class MmcHttpClient : HttpClient
{
  public MmcHttpClient(HttpClientHandler handler, bool disposeHandler) : 
    base(App.Handler, disposeHandler)
  {
    BaseAddress = new Uri("http://localhost:65066/");
    DefaultRequestHeaders.Accept.Clear();
    DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  }
}

      



You can read about it here

+4


source







All Articles