首页 > 解决方案 > 登录 API 方法在 Xamarin 表单中返回 400 错误请求

问题描述

我在 Xamarin 中有一个登录 API 方法,我正在使用 .net 核心项目。Web 应用程序中的后端登录在我登录后完美返回令牌,但在 Xamarin 的客户端我遇到了麻烦它作为响应返回 400 错误请求。我检查了 API,一切似乎都很好。我在请求的标头中传递了令牌以及凭据,我正在检查请求。这是客户端API:

  public async Task<string> Login(string email, string password)
        {
            var urlLogin = "http://10.0.2.2:5000/api/Token/";
            var formContent = new FormUrlEncodedContent(new[]
                {
              new KeyValuePair<string, string>("username", email),
              new KeyValuePair<string, string>("password", password),
              new KeyValuePair<string, string>("grant_type", "password")
            });

            var httpClient = new HttpClient();
            var authData = string.Format("{0}:{1}", email, password);
            var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authHeaderValue);
            var json = JsonConvert.SerializeObject(formContent);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                httpClient.DefaultRequestHeaders.Accept.Clear();
                var responseMessage = httpClient.PostAsync(urlLogin, content).Result;
                if(responseMessage.IsSuccessStatusCode)
                {
                    await App.Current.MainPage.DisplayAlert("Login succesful!", "Welcome", "ok", "cancel");
                    await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new UsersPage());
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Wrong credentials", "Please try again!", "ok", "cancel");
                }
               
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                throw;
            }




            return "";
        }

服务器端登录api :

   
   [HttpPost]
   [AllowAnonymous]
   public async Task<IActionResult> Post(User userData)
        {
            if (userData != null && userData.Email != null && userData.Password != null)
            {
                var user = await GetUser(userData.Email, userData.Password);

                if (user != null)
                {
                    //create claims details based on the user information
                    var claims = new[] {
                    new Claim(JwtRegisteredClaimNames.Sub, config["Jwt:Subject"]),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim("Id", user.Id.ToString()),
                    new Claim("Name", user.Name),
                    new Claim("Phone", user.Phone.ToString()),
                    new Claim("Email", user.Email),
                    new Claim ("ConfPassword",user.ConfPassword)
                   };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"]));

                    var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(config["Jwt:Issuer"], config["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(1), signingCredentials: signIn);

                    return Ok(new JwtSecurityTokenHandler().WriteToken(token));
                }
                else
                {
                    return BadRequest("Invalid credentials");
                }
            }
            else
            {
                return BadRequest();
            }
        }
        private async Task<User> GetUser(string email, string password)
        {
            return await _context.User.FirstOrDefaultAsync(u => u.Email == email && u.Password == password);
        }

用户.cs

   public class User
    {
        public int Id { get; set; }
       
        public string Name { get; set; }

        public string Email { get; set; }
     
        public string Phone { get; set; }
     
        public string Password { get; set; }
      
        public string ConfPassword { get; set; }
    }

有人可以帮我弄清楚 API 有什么问题吗?我是使用移动 API 的新手,所以请多多包涵。

标签: apiasp.net-coreauthenticationxamarin.forms

解决方案


我已经设法让它按照@Jason 的建议工作。这是客户端的工作方法:

  public async Task<string> Login(User user)
        {
            var urlLogin = "http://10.0.2.2:5000/api/Token/";
            var httpClient = new HttpClient();
            var authData = string.Format("{0}:{1}", user.Email, user.Password);
            var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authHeaderValue);
            var json = JsonConvert.SerializeObject(user);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                httpClient.DefaultRequestHeaders.Accept.Clear();
                var responseMessage = httpClient.PostAsync(urlLogin, content).Result;
                if(responseMessage.IsSuccessStatusCode)
                {
                    await App.Current.MainPage.DisplayAlert("Login succesful!", "Welcome", "ok", "cancel");
                    await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new UsersPage());
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Wrong credentials", "Please try again!", "ok", "cancel");
                }
               
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                throw;
            }




            return "";
        }


推荐阅读