从 Xamarin 或 Maui 调用时,为什么我的 API 返回 401?

问题描述 投票:0回答:0

我之前遇到过一个问题,我已经解决了我无法从毛伊岛调用 http,或者在应用程序启动时使用异步,这很痛苦。我现在已经过去了。我这样创建 HttpClient:

   private HttpClientHandler GetInsecureHandler()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
            {
                if (cert.Issuer.Equals("CN=localhost"))
                    return true;
                return errors == System.Net.Security.SslPolicyErrors.None;
            };
            return handler;
        }
        private HttpClient CreateHttpClient(string authToken)
        {
            HttpClientHandler handler = GetInsecureHandler();
            var httpClient = new HttpClient(handler);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            if (!string.IsNullOrEmpty(authToken))
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
            }
            return httpClient;
        }

然后我这样称呼它:

  var uri = new Uri(_baseLoginUrl + "account/login");
            string json = JsonSerializer.Serialize<LoginModel>(login, _serializerOptions);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                // You can't do async calls before your UI has shown.
                var response = _client.PostAsync(uri, content).Result;

此代码始终返回 401。相同的 API 在 Postman 中工作,它被标记为 [AllowAnonymous] 并返回一个令牌。我开始创建一个 Xamarin 应用程序 b/c 我在毛伊岛遇到了很多问题,但它们似乎是一样的。我认为错误消息是错误的,但我不知道发生了什么。

xamarin xamarin.android maui
© www.soinside.com 2019 - 2024. All rights reserved.