如何从返回的 API 响应中读取对象值?

How to read object value from returned API response?

我有一个 Web API,它将验证来自客户端(控制台)的登录,我想从控制台返回的响应中检索对象(内容)。这是 API 代码的片段:

[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”,而不是对象。如果您能帮助我,请提前致谢。

由于响应的内容是string,您可以通过将response.Content读取为string:

来实现
var errorMessage = await response.Content.ReadAsAsync<string>();

将其放在 else 语句中。

else
{
    var errorMessage = await response.Content.ReadAsAsync<string>();
    Console.WriteLine(response.StatusCode.ToString());
    return token;
}