Xamarin Android httpClient.getAsync导致异常

时间:2018-02-19 15:40:55

标签: c# .net rest xamarin.android rest-client

当我打电话

public static async Task<User> GetUserAsync(string name)
    {
        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Resource.RestBaseURI);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("APIKey", Resource.APIKey);

                var responseMessage = await client.GetAsync($"api/Users/{name}");
                if (!responseMessage.IsSuccessStatusCode)
                    throw new HttpResponseException(responseMessage.StatusCode);
                var userDb = responseMessage.Content.ReadAsAsync<UserDb>().Result;

                if (userDb == null)
                    throw new HttpResponseException(HttpStatusCode.NotFound);

                var user = DbClientConverter.UserDbToUser(userDb);

                user.RefuelEntityList = await RefuelEntityCommunicator.GetRefuelEntitiesAsync(user);

                return user;
            }
        }
        catch (HttpResponseException httpResponseException)
        {
            throw new HttpResponseException(httpResponseException.Response.StatusCode);
        }
        catch (HttpRequestException httpRequestException)
        {
            throw new HttpRequestException(httpRequestException.Message, httpRequestException);
        }
        catch (Exception exception)
        {
            throw new Exception(exception.Message, exception);
        }
    }

在Xamarin Android上

await client.GetAsync在第12行导致异常:

  

“'System.Net.Http.FormattingUtilities'的类型初始化程序引发异常”

WPF应用程序中使用的相同代码没有问题。

任何想法如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

解决方案1:似乎某些依赖项已被破坏。您是否尝试重新安装NuGet包?

从程序包管理器中,运行Update-Package Microsoft.AspNet.WebApi -reinstall。

解决方案2:使用NuGet安装Web API 2.1 WebHost。

解决方案3:安装包Microsoft.AspNet.WebApi -Version 5.x.x

https://forums.xamarin.com/discussion/85204/problem-is-could-not-load-type-system-net-http-formattingutilities

答案 1 :(得分:0)

而不是

client.DefaultRequestHeaders.Add("APIKey", Resource.APIKey);

使用

client.DefaultRequestHeaders.TryAddWithoutValidation("APIKey", Resource.APIKey);

这是因为&#34; APIKey&#34;这是一个非标准的自定义标题

答案 2 :(得分:0)

我认为ReadAsAsync扩展方法存在问题。 有关自定义解决方案,请参阅here