c# - 来自 PCL 的 Xamarin WebAPI 调用

标签 c# asp.net-web-api xamarin async-await dotnet-httpclient

我正在尝试开发一个 Xamarin.Forms 或 Xamarin.iOS/Xamarin.Droid native 应用程序,它可以对我的服务器进行 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;
        }
    }
}

我在网上找不到任何关于如何使其工作的好的教程,非常感谢这方面的任何帮助。

最佳答案

您正在混合异步/等待和阻塞调用.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/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;
    }
}

关于c# - 来自 PCL 的 Xamarin WebAPI 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44392196/

相关文章:

xamarin - 将GestureRecognizer添加到gridview中的行

c# - 我的团队在 asp.net 购物车项目中工作。是否可以集成 First Data Alternative Payment?

c# - 处理 null 返回的静态方法

c# - 版本控制 API 端点

asp.net - 在API方法中返回HttpStatusCode

c# - 在 Web Api 2 中启用 CORS

c# - 如何高效地将 IList<byte> 转换为 byte[]?

c# - FormClosing事件中的Application.DoEvents

c# - 何时在并发中使用锁语句

android - Xamarin:强制关闭应用程序时,重复 ScheduledJob 会导致崩溃