Xamarin WebAPI call from PCL



我正在尝试开发xamarin.forms或xamarin.ios/xamarin.droid本机应用程序,该应用程序可以对我的服务器进行Web API调用。我遇到了一个错误,说 HttpRequestException投掷了。一旦我搜索解决方案,它说这是因为它无法到达插座,但是我无法将其安装到PCL项目中。因此,我检查了解决方案,他们说要使用代理来达到服务。

这是我的问题。我已经尝试在PCL中制作代理,以连接到.droid或.ios项目中的服务,以便他们可以使用插座(尽管我认为该服务不应该在App Project本身中,因为重复代码(。但是代理类无法参考该服务,因为它不在项目中。

这是我的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;
        }
    }
}

我在网上找不到有关如何使其工作的好教程,并且在此方面的任何帮助将不胜感激。

您正在混合异步/等待和阻止调用.Result

public async Task<string> GET(string uri) {
    //...other code removed for brevity
    var response = Client.GetAsync(fullUri).Result;
    //...other code removed for brevity
}

导致僵局导致您无法到达插座。

使用async/等待时,您需要一直在异步,避免阻止 .Result.Wait()等呼叫。

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 = await Client.GetAsync(fullUri);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    } catch (Exception e) {
        return null;
    }
}

最新更新