【发布时间】:2017-06-06 14:03:59
【问题描述】:
我正在尝试开发一个 Xamarin.Forms 或 Xamarin.iOS/Xamarin.Droid 本机应用程序,它可以对我的服务器进行 Web API 调用。我收到错误提示 HttpRequestException 抛出。一旦我搜索了一个解决方案,它说这是因为它无法到达套接字,但我无法将它安装到 PCL 项目中。所以我检查了这个解决方案,他们说使用代理来访问服务。
这是我的问题。我曾尝试在 PCL 中创建代理以连接到 .Droid 或 .iOS 项目中的服务,以便他们可以使用套接字(尽管我认为该服务不应该在应用程序项目本身中,因为代码重复)。但是代理类无法引用该服务,因为它不在项目中。
这是我的RestService 课程。
public class RestService : IRestService
{
private const string BASE_URI = "http://xxx.xxx.xxx.xxx/";
private HttpClient Client;
private string Controller;
/**
* Controller is the middle route, for example user or account etc.
*/
public RestService(string controller)
{
Controller = controller;
Client = new HttpClient();
}
/**
* uri in this case is "userId?id=1".
*/
public async Task<string> GET(string uri)
{
try
{
Client.BaseAddress = new Uri(BASE_URI);
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var fullUri = String.Format("api/{0}/{1}", Controller, uri);
var response = Client.GetAsync(fullUri);
string content = await response.Result.Content.ReadAsStringAsync();
return content;
}
catch (Exception e)
{
return null;
}
}
}
我在网上找不到任何关于如何使它工作的好的教程,非常感谢这方面的任何帮助。
【问题讨论】:
-
刚刚查看了两个链接。这两种解决方案都不是问题,因为我没有使用 IIS,并且给定的 url 适用于邮递员。
-
@Tomaltach 总体上避免阻塞呼叫。将其移至响应没有任何区别。它仍然是一个阻塞调用
-
你可以试试改装,在PCL里好用github.com/paulcbetts/refit
标签: c# asp.net-web-api xamarin async-await dotnet-httpclient