【发布时间】:2022-02-11 17:00:53
【问题描述】:
我有一个 Web API,它将验证来自客户端(控制台)的登录,我想从控制台返回的响应中检索对象(内容)。 API代码的sn-p如下:
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] Login login)
{
if (ModelState.IsValid)
{
var user = await this.userManager.FindByNameAsync(login.Username);
if (user != null)
{
var passwordCheck = await this.signInManager.CheckPasswordSignInAsync(user, login.Password, false);
if (passwordCheck.Succeeded)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.config["Tokens:Key"]));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
this.config["Tokens:Issuer"],
this.config["Tokens:Audience"],
claims,
expires: DateTime.UtcNow.AddHours(3),
signingCredentials: credentials
);
return Ok(new
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = token.ValidTo
});
}
else
{
return Unauthorized("Wrong password or email!");
}
}
else
{
return Unauthorized("Must not empty");
}
}
return BadRequest();
}
如果我尝试测试来自 Postman 的调用,它将达到我的预期:
但是,我不知道如何从控制台应用程序中获得相同的结果。代码如下:
static async Task<JwtToken> Login()
{
Login login = new();
JwtToken token = null;
Console.Write("Username: ");
login.Username = Console.ReadLine();
Console.Write("Password: ");
login.Password = Console.ReadLine();
HttpResponseMessage response = await client.PostAsJsonAsync("account/login", login);
if (response.IsSuccessStatusCode)
{
token = await response.Content.ReadAsAsync<JwtToken>();
Console.WriteLine("Token: {0}\nValid to: {1}",token.Token,token.Expiration);
return token;
}
else
{
Console.WriteLine(response.StatusCode.ToString());
return token;
}
}
而不是对象,我只会得到“BadRequest”或“Unauthorized”。如果您能帮助我,请提前致谢。
【问题讨论】:
-
你的意思是你想得到“错误的密码或电子邮件”吗?
-
是的,这是假定的对象值
标签: c# asp.net-core asp.net-core-mvc asp.net-core-webapi