ASP.NET Core Web API - 如何基于 HttpStatus 在第三方 API 中返回响应

问题描述 投票:0回答:0

在我的 ASP.NET Core-6 Web API 中,我正在使用第三方 API,返回的响应应该基于 Http Status

供应商给了我这些回复:

BadRequest:

{
  "ResponseCode": "88",
  "ResponseDescription": "sample response"
}

成功请求:

{
  "Token": "987654567873",
  "ExpiryDate": "2023-04-01T14:15:22Z",
  "ResponseCode": "00",
  "ResponseDescription": "sample response"
}

所以为了实现目标,我有这些DTO:

StudentRequestDto:

public class StudentRequestDto
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string StudentCode { get; set; }
}

BadRequestDto

public class BadRequestDto
{
    public string ResponseCode { get; set; }
    public string ResponseDescription { get; set; }
}

成功请求Dto

public class SuccessRequestDto
{
    public string Token { get; set; }
    public string ExpiryDate { get; set; }
    public string ResponseCode { get; set; }
    public string ResponseDescription { get; set; }
}

GenericResponse

public class GenericResponse
{
    public HttpStatusCode StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

所以我在这里实现了:

    public async Task<SuccessRequestDto> RegisterStudent(StudentRequestDto payload)
    {
        var response = new SuccessRequestDto();
        var badResponse = new BadRequestDto();
        _genericResponse = new GenericResponse();
        try
        {
            _tokenService = new TokenService(_tokenHelper, MemoryCache, _tokenLogger);
            string defaultToken = await _tokenResetService.GenerateToken();

            var defaultHeaderInfo = new Dictionary<string, string>();
            defaultHeaderInfo.Add("Authorization", $"Bearer {defaultToken}");
            _genericResponse = await _myHelper.StudentTokenGen(defaultHeaderInfo, payload);
            if (_genericResponse.StatusCode == HttpStatusCode.OK || _genericResponse.StatusCode == HttpStatusCode.Accepted)
            {
                response = JsonConvert.DeserializeObject<SuccessRequestDto>(_genericResponse.ResponseMessage);
                return response;
            }
            else
            {
            }
        }
        catch (Exception ex)
        {
            response = JsonConvert.DeserializeObject<SuccessRequestDto>(_genericResponse.ResponseMessage);
            return response;
        }
    }

正如我之前所说,我正在将请求发送给第三方,然后得到回复。

我想要实现的是,如果成功,它应该返回 SuccessRequestDto,否则它应该返回 BadRequestDto。

如何重写代码来实现这一点?

c# asp.net-core asp.net-web-api httpclient
© www.soinside.com 2019 - 2024. All rights reserved.