c# - 如何在 Visual Studio 2015 中的 Xamarin.forms 可移植应用程序中调用 REST Api

标签 c# rest visual-studio-2015 xamarin.forms portable-class-library

我正在尝试使用 REST 服务连接 Xamarin.Forms 可移植应用程序。我使用的是 Visual Studio 2015 企业版。

Rest 服务在本地发布,通过 url 运行良好。
当我试图在应用程序中调用我的 Rest 服务时。它抛出一个异常:

{System.Threading.Tasks.TaskCanceledException} with "One or more errors occurred."

ServiceWrapper.cs 中的 C# 代码:

public async Task<string> GetData()
        {
            try
            {
                var client = new HttpClient(new NativeMessageHandler());
                client.BaseAddress = new Uri("http://ipaddress/");
                client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
                var response = client.GetAsync("IRESTApi.svc/xml/12").Result;
                string content = await response.Content.ReadAsStringAsync();
                return content;
                //using (var client = new HttpClient())
                //{
                //    var result = await client.GetAsync("http://ipaddress/IRESTApi.svc/xml/12");
                //    return await result.Content.ReadAsStringAsync();
                //}
            }

            catch (Exception ex)
            {
                var t = ex.Message;
                return t;
            }
        }

我正在使用 this 尝试上述方法android 设备中的引用。请帮忙。

最佳答案

试试这个 :D

  public interface IGetData
  {
       Task<string> GetApiData();
  }

  public class GetData : IGetData
  {

    public async Task<string> GetApiData()
    {
      var client = new HttpClient();
      var response = await client.GetAsync(string.Format("http://mysite/api/Data"));
      var responseString = await response.Content.ReadAsStringAsync();
      return responseString; 
    }

   }

关于c# - 如何在 Visual Studio 2015 中的 Xamarin.forms 可移植应用程序中调用 REST Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38759857/

相关文章:

c# - 将 dll 转换为 csproj 或 sln

c# - 格式化我的字符串

c# - 使用 Entity Framework (C#) 覆盖 PostgreSql 中的序列

java - 通过 POST : getting an SSL exception 将 JSON 格式的工作申请发送到 REST API

java - 使用正确的凭据访问基于 REST 的 Web 服务时出现响应代码 401

git - 我可以同时从 VS 2015 连接到 VSTS 和 GitHub 吗?

visual-studio-2015 - 错误 "The OutputPath property is not set for project"VS 2015

visual-studio - VS2015 在 DebuggerStepTrough 中抛出捕获的异常?

c# - 错误 : 'Input string was not in a correct format.'

c# - 来自控制台应用程序的 HTTPS?