After first request HttpClientHandler is disposed

3

I want to send two request from my ViewModel (first - GET and then - POST) using HttpClient. GET request completes without any error. But if then I send POST request I got exception:

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

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

I'm using one HttpClientHandler for both requests (becouse I store Cookies in that 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}
c#
windows-phone
httpclient
asked on Stack Overflow Sep 29, 2014 by feeeper • edited Sep 29, 2014 by feeeper

1 Answer

4

It was my fault. After adding second param (disposeHandler) to HttpClient constructor all works good:

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

answered on Stack Overflow Sep 30, 2014 by feeeper • edited Sep 30, 2014 by feeeper

User contributions licensed under CC BY-SA 3.0