首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ObjectDisposedException on HttpClient

ObjectDisposedException on HttpClient
EN

Stack Overflow用户
提问于 2015-03-31 13:31:16
回答 3查看 32.5K关注 0票数 24

我有一个带有多个API调用的Windows通用项目。一种方法拒不起作用,即使我的其他调用也是如此。我尝试过using关键字,认为它可以解决这个问题。

职能:

代码语言:javascript
复制
public async Task<User> GetNewUser(string user_guid, OAuthTokens OAuth)
{
    String userguidJSON = VALIDJSON_BELIEVE_ME;
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", Encrypt(OAuth.Accesstoken));

        using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_USERS + "/data"))
        {
            req.Content = new StringContent(userguidJSON, Encoding.UTF8, "application/json");
            await httpClient.SendAsync(req).ContinueWith(respTask =>
            {
                Debug.WriteLine(req.Content.ReadAsStringAsync()); //Error is thrown ono this line
            });
            return null;
        }
    }
}

编辑

代码语言:javascript
复制
public async Task<User> GetNewUser(string user_guid, OAuthTokens OAuth)
{
    String userguidJSON = VALIDJSON_BELIEVE_ME;
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", Encrypt(OAuth.Accesstoken));

        using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_USERS + "/data"))
        {
            req.Content = new StringContent(userguidJSON, Encoding.UTF8, "application/json");
            await httpClient.SendAsync(req);
            var result = await req.Content.ReadAsStringAsync(); //Cannot access a disposed object. Object name: 'System.Net.Http.StringContent'.
            Debug.WriteLine(result);
            return null;
        }
    }
}

堆叠痕迹

代码语言:javascript
复制
 at System.Net.Http.HttpContent.CheckDisposed()
   at System.Net.Http.HttpContent.ReadAsStringAsync()
   at Roadsmart.Service.RoadsmartService.<GetNewUser>d__2e.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 Roadsmart.ViewModel.SettingsPageViewModel.<SetNewProfilePicture>d__1e.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()
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-03-31 13:40:25

引发ObjectDisposedException是因为要在HttpRequestMessageHttpClient完成之前对其进行处理。

注意,req.Content.ReadAsStringAsync()是一个异步方法。在配置HttpClient之前,您需要等待它完成。

而且,您似乎是在req.Content中调用req.Content,难道不是response.Content吗?

代码语言:javascript
复制
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_USERS + "/data"))
{
    req.Content = new StringContent(userguidJSON, Encoding.UTF8, "application/json");
    var response = await httpClient.SendAsync(req);
    var result = await response.Content.ReadAsStringAsync();//await it
    Debug.WriteLine(result);
    return null;
}

在处理异步/等待时,几乎没有理由使用ContinueWith。所有这些都是由编译器为您完成的。

票数 24
EN

Stack Overflow用户

发布于 2017-01-10 15:58:25

抛出ObjectDisposedException的实际原因是HttpClient在完成请求后立即处理Content。看一看文档

因此,如果您需要读取Request的内容,例如在测试中,请确保在调用SendAsync之前读取它。

票数 18
EN

Stack Overflow用户

发布于 2015-03-31 14:09:24

您正在访问请求内容,而不是响应。

代码语言:javascript
复制
await httpClient.SendAsync(req);
var result = await req.Content.ReadAsStringAsync(); //Cannot access a disposed object. Object name: 'System.Net.Http.StringContent'.

应该是

代码语言:javascript
复制
var response = httpClient.SendAsync(req);
var result = await response.Content.ReadAsStringAsync();
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29369945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档