api - 登录 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 的新手,所以请多多包涵。
解决方案
我已经设法让它按照@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 "";
}
推荐阅读
- java - 验证用户输入的整数时无法转换类型
- python - 如何创建一个熊猫数据框,其中包含 2 个数据框,一个作为列,一个作为行
- python - 如何在django中自定义一个onetomany关系的序列化器数据
- node.js - ES6/TypeScript 动态导入 - 由于静态导入(Nodejs CLI)而导致启动时间缓慢
- python - 如何生成满足某些条件的三个随机整数?
- reactjs - react-hook-form 的 DefaultValues 未将值设置为 React JS 中的输入字段
- firebase - React Native:使用哪个 firebase 存储 npm 包?
- javascript - Suitescript2.0 中的 Netsuite record.save 返回 200OK 但未创建记录(但同样适用于 SuiteScript1.0)
- apache-kafka - 为什么消费者获取消息时 Kafka 主题队列不为空?
- python - scapy.arping() 或 netdiscover 未在 kali linux 2020.1 中检测到任何连接到 wifi 的客户端