【问题标题】:GetStringAsync method not respondingGetStringAsync 方法没有响应
【发布时间】:2018-10-09 21:08:43
【问题描述】:

我正在尝试从数据库的 ASPNetUsers 表中获取一些自定义列值(经度、纬度),当我发送 Get 请求抛出浏览器时,我得到 200 ok 请求的 json .. 但是当我尝试使用GetStringAsync 反序列化我的 xamarin 应用程序中的响应我没有得到任何响应。

在 AccountController 类中

// POST api/Account/GetUserPostion
    [Route("GetUserPostion")]

    public LocationDataToPostAsync GetUserPostion()
    {
        var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
        var manager = new ApplicationUserManager(store);
        LocationDataToPostAsync locationData = new LocationDataToPostAsync();


        var model = manager.FindById(User.Identity.GetUserId());
        locationData.UserId = User.Identity.GetUserId();
        if (model.Longitude != null) locationData.Longitude = (double) model.Longitude;
        if (model.Latitude != null) locationData.Latitude = (double) model.Latitude;

        return locationData;



    }

在 xamarin 表单应用程序的 ApiService 类中

public async Task<LocationDataToPostAsync> GetUserLocationAsync(string accessToken)
    {
        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

        var json = await client.GetStringAsync("http://10.0.2.2:45455/api/Account/GetUserPostion");

        var location = JsonConvert.DeserializeObject<LocationDataToPostAsync>(json);

        return location;

    }

【问题讨论】:

  • 您在哪里以及如何拨打GetUserLocationAsync?是否抛出任何异常或执行只是停止?在后一种情况下,这听起来像是死锁,表明您错误地调用了该方法。
  • 在一个名为 MapPageViewModel 的类中 public async Task GetUserLocation() { var accesstoken = Settings.AccessToken; UserCurrentLocation = 等待 _apiServices.GetUserLocationAsync(accesstoken);返回用户当前位置; }
  • 执行没有超出getstringasync中的await ..没有抛出异常...可能调用有问题..但至少json var不应该返回某物 ?!因为就像我说的,当我从浏览器调用它时,响应是 200 ok 以及请求的数据?!
  • 调用async方法的最顶层,是怎么做的?你是打电话给.Result 还是.GetAwaiter().GetResult() 来处理这个任务,或者你在做什么?无论如何,请尝试在 await 任务的任何地方添加 .ConfigureAwait(false),除非您特别需要返回到您来自的上下文。
  • 谢谢@Cheesebaron .. 我将 .ConfigureAwait(false) 添加到 await 调用中,现在可以使用了..

标签: json web-services xamarin asp.net-web-api xamarin.forms


【解决方案1】:

从您的代码中不清楚是在等待Task,还是您在Task 上调用.Result.GetAwaiter().GetResult()。但是,正如我们在 cmets 中发现的那样,添加 .ConfigureAwait(false) 解决了您的问题。

这表示代码无法返回到它来自的上下文,所以添加.ConfigureAwait(false)代码不会返回到上下文。

在您的情况下,上下文可能是 UI 线程,当它尝试返回时,UI 线程被阻止。

UI 线程被阻塞的最可能情况是您以错误的方式调用了您的任务。如果你在 UI 线程上使用 .Result 调用它,你会同步阻塞 UI 线程,因此任何试图返回 UI 线程的东西都会死锁,因为你正在阻塞它。

这里的简单解决方法是在您的代码中添加.ConfigureAwait(false)。更好的解决方案是不要通过等待任务来阻塞 UI 线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    相关资源
    最近更新 更多