我正在尝试使用 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/