简体   繁体   English

来自 PCL 的 Xamarin WebAPI 调用

[英]Xamarin WebAPI call from PCL

I am trying to develop a Xamarin.Forms or Xamarin.iOS/Xamarin.Droid native app which can make a Web API call to my server.我正在尝试开发一个 Xamarin.Forms 或 Xamarin.iOS/Xamarin.Droid 本机应用程序,它可以对我的服务器进行 Web API 调用。 I get the error saying HttpRequestException thrown.我收到错误说HttpRequestException抛出。 Once I searched for a solution, it says that it is because it can't reach the socket, but I am unable to install it to a PCL project.一旦我搜索了一个解决方案,它说这是因为它无法到达套接字,但我无法将其安装到 PCL 项目中。 So I check the solution for this and they said to use a proxy to reach the service.所以我检查了这个解决方案,他们说使用代理来访问服务。

Here is my problem.这是我的问题。 I have tried making a Proxy in the PCL to connect to a service in the .Droid or .iOS projects so they can use the sockets, (although I don't think the service should be in the app project itself because duplicate code).我曾尝试在 PCL 中创建一个代理以连接到 .Droid 或 .iOS 项目中的服务,以便他们可以使用套接字,(尽管我认为该服务不应该在应用程序项目本身中,因为重复代码)。 But the proxy class is not able to reference the the service because it is not in the project.但是代理类无法引用该服务,因为它不在项目中。

This is my RestService class.这是我的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;
        }
    }
}

I cannot find any good tutorials online on how to get this to work and any help in this regards would be much appreciated.我在网上找不到任何关于如何使其工作的好的教程,在这方面的任何帮助将不胜感激。

You are mixing async/await and blocking calls .Result您正在混合 async/await 和阻塞调用.Result

public async Task<string> GET(string uri) {
    //...other code removed for brevity

    var response = Client.GetAsync(fullUri).Result;

    //...other code removed for brevity
}

which is causing a deadlock resulting in you not being able to get to socket.这导致死锁,导致您无法访问套接字。

When using async/await you need to go async all the way and avoid blocking calls like .Result and .Wait() .使用 async/await 时,您需要一直进行异步并避免阻塞调用,例如.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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM