Home > database >  How to read object value from returned API response?
How to read object value from returned API response?

Time:02-11

I have a web API that will validate a login from a client (console) and I want to retrieve the object (content) from the response returned from the console. Here is the snippet of the API code:

[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();
}

If I tried to test the call from Postman, it will get what I expected:

This is the image

However, I don't know how to get the same result from the console app. Here is the code:

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;
    }

}

And instead of the object, I will just get "BadRequest" or "Unauthorized". Thanks in advance if you can help me.

CodePudding user response:

As the response's content is a string, you can achieve by reading the response.Content as string:

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

Place it in else statement.

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