客户端多个api响应处理



我的api有一个返回多种响应类型的方法:GetTokenResponseErrorsResponseErrorResponse

[HttpPost("token")]
[ProducesResponseType(typeof(GetTokenResponse), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(ErrorsResponse), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(ErrorResponse), (int)HttpStatusCode.Forbidden)]
public async Task<IActionResult> GetToken([FromBody] GetTokenRequest request)
{
try
{
var token = await _authService.LoginAsync(request.Email, request.Password);
return Ok(new GetTokenResponse { Token = token });
}
catch (Exception ex) when (ex is UserNotFoundException || ex is InvalidPasswordException)
{
return BadRequest(new ErrorsResponse("Invalid username or password."));
}
catch (EmailNotConfirmedException ex)
{
return StatusCode((int)HttpStatusCode.Forbidden, new ErrorResponse(ex.Message));
}
}

并且客户端服务具有使请求的方法

public async Task<bool> LoginAsync(GetTokenRequest request)
{
var response = await _client.PostAsJsonAsync($"{_apiUrl}{Requests.Token}", request);
if (response.StatusCode != HttpStatusCode.OK)
{
return false;
}
var responseString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<GetTokenResponse>(responseString);
await Authenticate(result.Token, request.Email);
return true;
}

在当前的实现方法中,可以返回true或false,只处理GetTokenResponse,但我想处理所有的响应类型。事实上这就是问题所在。最好的方法是什么?我考虑过从服务返回响应内容,并在调用方解析响应类型,为响应创建一个基本响应类型\包装器,但最佳实践说明了什么?

我添加了抛出异常的扩展方法EnsureSuccess((

public async Task LoginAsync(GetTokenRequest request)
{
var response = await _client.PostAsJsonAsync($"{_apiUrl}{Requests.Token}", request);
var result = await response.EnsureSuccess<GetTokenResponse>();
await Authenticate(result.Token, request.Email);
}

然后在页面上

public async Task ExecuteLogin()
{
try
{
await AuthService.LoginAsync(_request);
NavigationManager.NavigateTo("/");
}
catch (BadRequestException ex)
{
var response = ex.Response.Deserialize<ErrorsResponse>();
Errors = response.Result.Messages;
}
catch (ForbiddenException ex)
{
var response = ex.Response.Deserialize<ErrorResponse>();
Errors = new List<string> { response.Result.Message };
}
}

相关内容

  • 没有找到相关文章

最新更新