【问题标题】:HttpClient ReadAsAsync does not deserializeHttpClient ReadAsAsync 不反序列化
【发布时间】:2014-07-21 01:01:54
【问题描述】:

我不确定我遇到的问题是否与我使用 Task 的方式有关,或者我是否没有正确使用 ReadAsAsync。我遵循我在这里找到的模式:

http://blogs.msdn.com/b/henrikn/archive/2012/02/11/httpclient-is-here.aspx

背景: 我要反序列化的对象是 POCO。属性没有属性。它只是几个值类型属性和几个集合属性。 REST 服务似乎也可以正常工作。当我查看服务返回的 JSON 时,它似乎没问题。 使用 Web API 2.1 5.1.2

问题: .. 正在调用 HttpResponseMessage.Content.ReadAsAsync()。有时它起作用(返回一个对象),有时它不起作用(抛出“线程被中止”或返回 null)。似乎内容属性只能读取一次,后续读取会引发错误。请参阅下面代码中的 cmets。

相关问题: HttpContent.ReadAsAsync Deserialization issue

问题似乎与我的相似。答案表示一个错误,但这已经超过两年了。

代码:

[TestMethod]
    public void AddSiteTest()
    {
        // Use POST to create a resource i.e. insert.  Use PUT to update.

        Site site = new Site {SiteName = "Test", Active = true, URI="www.test.com" };
        Site newSite = null;

        client.PostAsJsonAsync<Site>(baseURI + "/Sites/AddSite?securityKey="+ SecurityKey, site).ContinueWith(x =>
            {
                HttpResponseMessage response = x.Result;

                response.EnsureSuccessStatusCode();

                if (response.IsSuccessStatusCode)
                {
                    try
                    {

                        string str = Task.Run(() => response.Content.ReadAsStringAsync()).Result;      // yep its json and it is a proprety serialized object

                        // Method 1 (preferred... ):
                        //Site siteA = Task.Run(() => response.Content.ReadAsAsync<Site>()).Result;      // usuallly throws if content has been read  


                        // Method 2:
                        Site siteB = response.Content.ReadAsAsync<Site>().Result;                      // usully returns a valid result (when I dont put a breakpoint on it). Does not deadlock.

                        // Method 3:
                        response.Content.ReadAsAsync<Site>().ContinueWith(d => 
                        {
                            Site siteC = d.Result;                                                    // returns null
                        });

                    }
                    catch (Exception ex)
                    {
                        string y = ex.Message;
                    }
                }
            });
    }

【问题讨论】:

  • 您的延续可能在请求完成之后运行。考虑使用 async/await 代替 .ContinueWith

标签: c# asp.net-web-api2


【解决方案1】:

尝试使用等待:

string str = await response.Content.ReadAsStringAsync();

而且您必须在方法中的 void 之前添加 async。

【讨论】:

  • 我不想使用异步测试方法。在生产中运行它的方法不是异步的。异步在调用堆栈中一直向上传播。如何调用这个方法并等待?
猜你喜欢
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多