简体   繁体   English

客户端多个 api 响应处理

[英]Client-side multiple api responses handling

My api has a method that returns multiple response types: GetTokenResponse , ErrorsResponse , ErrorResponse .我的 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));
    }
}

and the client side service has a method to make the request并且客户端服务有一个方法来发出请求

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

In the current implementation method can return either true or false, only GetTokenResponse is processed but I want to handle all response types.在当前的实现方法中可以返回true 或false,只处理GetTokenResponse但我想处理所有响应类型。 Actually this is the question.其实就是这个问题。 What is the best way to do it?最好的方法是什么? I thought about returning response content from the service and parsing response type on the caller side, creating a base response type \\ wrapper for responses but what do best practices say?我考虑过从服务返回响应内容并在调用方解析响应类型,为响应创建一个基本响应类型\\包装器,但最佳实践是什么?

I added extension method EnsureSuccess() that throws exceptions我添加了抛出异常的扩展方法确保成功()

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

Then on the page然后在页面

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM