我有一个场景,当登录失败时,Api 必须返回 UnAuthorized 结果。但是,从await HttpClient.PostJsonAsync(url, credentials);序列化 导致控制台出现 javascript 错误,导致登录页面无法按预期运行。这是我所拥有的。
API 代码:
[HttpPost("LoginV2")]
[SwaggerOperation(Tags = new[] { "Auth" })]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> LoginV2([FromBody] LoginDto login)
{
var result = await _signInManager.PasswordSignInAsync(login.Email, login.Password, false, false);
if (result.Succeeded)
{
var appUser = _userManager.Users.SingleOrDefault(r => r.UserName == login.Email);
var token = new TokenDto()
{
JwtToken = GenerateJwtToken(appUser),
RefreshToken = GenerateRefreshToken()
};
var appUserAuth = new IdentityWithTokenDto()
{
////......Omitted
};
return Ok(appUserAuth);
}
return Unauthorized();
}
Blazor 代码:
async Task SubmitCredentials()
{
var result = await Client.PostJsonAsync<IdentityWithTokenDto>(url, credentials);
loginFailure = string.IsNullOrEmpty(result.Token.JwtToken);
if (!loginFailure)
{
await tokenAuthenticationStateProvider.SetTokenAsync(result.Token.JwtToken, DateTime.Now.AddDays(1));
Navigation.NavigateTo("/",true);
}
}
我无法弄清楚如何处理未经授权的结果,因为 httpclient 会处理它,并且 blazor javascript 会向控制台抛出一个错误,从而阻止登录表单工作。这是正确的行为还是正确处理它的任何方法?
更新: 下面的答案指出了在这种情况下不使用PostAsJsonAsync<>并手动转换结果的解决方案。
这是更新的代码:
var response = await Client.PostAsJsonAsync(url, credentials);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsAsync<IdentityWithTokenDto>();
await tokenAuthenticationStateProvider.SetTokenAsync(data.Token.JwtToken, DateTime.Now.AddDays(1));
Navigation.NavigateTo("/", true);
}
else
{
//Update the UI
}