【问题标题】:Xamarin Portal Class Library Access ASP.NET Web ApiControllerXamarin 门户类库访问 ASP.NET Web ApiController
【发布时间】:2014-08-02 21:12:22
【问题描述】:

我正在尝试创建一个 PCL,该 PCL 将能够通过 Xamarin 在 Android、iOS 和 Windows Phone 中重复使用。类库的核心将用于与托管在 Windows Azure 上的 ASP.NET Web ApiController 进行通信。我很难让 HttpClient 工作。这是代码。

        public async Task<string> GetData()
    {
        string responseStr = null;

        using (var httpClient = new HttpClient())
        {
            httpClient.BaseAddress = new Uri("https://myapi.com/");
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var data = new { data1 = "1", data2 = "2" };
            var content = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            StringContent httpContent = new System.Net.Http.StringContent(content, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await httpClient.PostAsync("Events/GetData", httpContent);

            if (response.IsSuccessStatusCode)
            {
                responseStr = await response.Content.ReadAsStringAsync();
            }
        }
        return responseStr;
    }

如果我在控制台应用程序中使用此代码,它可以完美运行,但是当我在调试 Android 应用程序时尝试在 PCL 中做同样的事情时,它会到达await httpClient.PostAsyc 行,等待一两秒钟然后立即跳到方法的末尾,永不返回,永不抛出异常。

我不知道发生了什么,也不知道为什么这会在控制台应用程序中起作用,但在 PCL 中却不起作用。我在 Android 项目和 PCL 中都引用了必要的 HTTP 客户端库。

一天结束,我只需要一个允许我发布到 Web ApiController 并读回数据的解决方案。我尝试了许多解决方案,但似乎都没有。任何帮助将不胜感激。

【问题讨论】:

    标签: android xamarin dotnet-httpclient


    【解决方案1】:

    await 应该返回任务。捕获 Task 类型的对象并检查 Exception 和 Status 属性,而不是直接转换为 HttpResponseMessage (响应)和字符串 responseStr 在您的情况下。

    Task<HttpResponseMessage> response = await httpClient.PostAsync("Events/GetData", httpContent);
    // response.Exception
    // repsonse.Status
    

    Task<string> responseStr = await response.Content.ReadAsStringAsync();
    // responseStr.Exception
    // responseStr.Status
    

    通过这种方式,您将获得有关正在发生的事情的更多信息。某些平台(如 iOS)可能会拒绝连接到没有有效证书的服务器等。

    进一步参考:

    【讨论】:

      猜你喜欢
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 2019-07-26
      • 2014-07-07
      • 1970-01-01
      相关资源
      最近更新 更多