PCL文件中的HttpClient错误

时间:2015-08-26 13:34:38

标签: c# .net xamarin async-await portable-class-library

我刚刚在VS 2013中创建了一个PCL项目,并在我的项目中添加了以下Nuget包,并选择了所有可用的平台,因为我想在.NET和我的Xamarin项目中重复使用它。

  • Microsoft HTTP客户端库
  • Json.NET

但是在以下一行:

HttpResponseMessage response = await client.PostAsync(uri, content);

我收到以下错误:

Cannot await 
'System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>'

并在这一行:

return await response.Content.ReadAsStringAsync();

我收到以下错误:

Cannot await 'System.Threading.Tasks.Task<string>'

这是完整的代码,可以在我的通用应用程序的共享项目中正常工作。

    public static async Task<string> PostDataAsync<T>(string uriString, 
    T data, ContentType contentType, bool isWrapped)
    {
        HttpClient client = new HttpClient();

        Uri uri = new Uri(uriString);

        string wrappedName = data.GetType().Name;
        string postData = string.Empty;
        string prefix = string.Empty;
        string suffix = string.Empty;

        if (contentType == ContentType.Xml)
        {
            //postData = SerializerHelper.SerializeObjectToXML<T>(data, 
            //true, true, true, false);
        }
        else
        {
            if (isWrapped)
            {
                prefix = string.Concat("{\"", data.GetType().Name, "\":");
                suffix = "}";
            }
            postData = prefix + JsonConvert.SerializeObject(data) + suffix;
        }

        client.DefaultRequestHeaders.Accept.Add(new 
        MediaTypeWithQualityHeaderValue(contentType == 
        ContentType.Json ? "application/json" : "application/xml"));

       client.DefaultRequestHeaders.Host = uri.Host;

        StringContent content = new StringContent(postData,
        System.Text.Encoding.UTF8, contentType ==
        ContentType.Json ? "application/json" : "application/xml");

        HttpResponseMessage response = await client.PostAsync(uri, content);

        if (response.StatusCode == HttpStatusCode.NotFound)
            throw new NetworkConnectivityException();
        else if (response.StatusCode != HttpStatusCode.OK)
            throw new Exception(response.RequestMessage.ToString());

        return await response.Content.ReadAsStringAsync();
    }

这些只是我读过的一些文章,但没有一篇指向正确的解决方案:

我设法创造了一个工作功能,与上面的略有不同,但原则保持不变,但我不确定这是否是正确的方法,因为我&#39;我正在等待&#34;等待&#34;在函数内,而不是从调用它的应用程序。有人可能只想确认以下是否也可以?请注意,虽然它编译,但我还没有机会尝试使用Xamarin。

public static Task<U> PostDataAsync<T, U>(string baseAddress, string
requestUri, T data, ContentType contentType = ContentType.Json, 
bool isWrapped = true, double timeOut = 1200000)
    {
        string contentTypeString = (contentType ==
        ContentType.Json ? "json" : "xml");

        using (HttpClientHandler handler = new HttpClientHandler())
        {
            using (HttpClient client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri(baseAddress);
                client.Timeout = TimeSpan.FromMilliseconds(timeOut);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/" + 
                    contentTypeString));

                string postData = string.Empty;
                string prefix = string.Empty;
                string suffix = string.Empty;

                if (contentType == ContentType.Json)
                {
                    if (isWrapped)
                    {
                        prefix = string.Concat("{\"", 
                        data.GetType().Name, "\":");
                        suffix = "}";
                    }
                    postData = prefix + JsonConvert.
                    SerializeObject(data) + suffix;
                }
                else
                {

                }

                HttpRequestMessage request = new 
                HttpRequestMessage(HttpMethod.Post, requestUri);
                request.Content = new StringContent(postData,
                                                    Encoding.UTF8,
                                                    "application/" +
                contentTypeString);

                if (handler.SupportsTransferEncodingChunked())
                {
                    request.Headers.TransferEncodingChunked = true;
                }

                HttpResponseMessage response = null;
                string dataReturned = string.Empty;
                U dataObject = default(U);

                Task resp = client.SendAsync(request)
                      .ContinueWith(responseTask =>
                      {
                          response = responseTask.Result;
                          if (responseTask.Result.IsSuccessStatusCode)
                          {
                              Task<string> dataTask = 
                              response.Content.ReadAsStringAsync();

                              dataReturned = dataTask.Result.ToString();
                              dataObject = JsonConvert.
                              DeserializeObject<U>(FixJson
                               (dataReturned, "Result"));
                          }
                          else
                          {
                              dataReturned = "HTTP Status: " +
                              response.StatusCode.ToString() + 
                              " - Reason: " + response.ReasonPhrase;
                          }
                      });

                resp.Wait();

                return Task.Factory.StartNew(() => dataObject);
            }
        }
    }

我的第一个功能如何解决问题的任何想法?第二个功能好吗?

感谢。

1 个答案:

答案 0 :(得分:0)

安装NuGet软件包Microsoft.Bcl.Async,以便获得对asyncawait的支持。