【问题标题】:How to read object value from returned API response?如何从返回的 API 响应中读取对象值?
【发布时间】: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


【解决方案1】:

由于响应的内容是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;
}

【讨论】:

  • 谢谢,我只是明白该对象是作为内容主体的一部分返回的。这确实返回了我想要的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 2021-07-27
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
相关资源
最近更新 更多