在第一次请求后,HttpClientHandler被释放

时间:2014-09-29 16:20:32

标签: c# windows-phone httpclient

我想使用HttpClient从我的ViewModel发送两个请求(第一个--GET,然后是 - POST)。 GET请求完成,没有任何错误。但如果那时我发送POST请求我得到例外:

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

或者,如果我在GET之前运行POST请求 - POST完成正常并且GET - 以相同的异常失败。

我在两个请求中都使用了一个HttpClientHandler(因为我将Cookie存储在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"));
  }
}

堆栈跟踪:

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}

1 个答案:

答案 0 :(得分:4)

这是我的错。将第二个参数(disposeHandler)添加到HttpClient构造函数后,一切正常:

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"));
  }
}

您可以阅读here