0

我正在使用提供此操作的 API:

[HttpGet]
[SwaggerOperation(OperationId = nameof(GetUsers))]
[SwaggerResponse(StatusCodes.Status200OK, "Result", typeof(List<UserModel>))]
[ProducesResponseType(typeof(List<UserModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ErrorModel), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetUsers(string tenantId, int departmentId)
{
    // Magically queries the users and returns OK or detect something is wrong and returns BadRequest
    ...
}

此调用可以返回UserModel是否一切正常或ErrorModel请求是否错误的列表。

使用swaggerand autorest,我得到一个自动生成的客户端,该客户端具有此方法返回一个对象:

 public async Task<HttpOperationResponse<object>> GetUsersWithHttpMessagesAsync(string tenantId, int departmentId, string commitReference = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
   ...
}

在该方法中,算法检查状态代码。如果状态码是 200,那么它会构建一个列表UserModel

    // Deserialize Response
    if ((int)_statusCode == 200)
    {
        _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

        try
        {
            _result.Body = SafeJsonConvert.DeserializeObject<List<UserModel>>(_responseContent, DeserializationSettings);
        }
        catch (JsonException ex)
        {
            _httpRequest.Dispose();
            if (_httpResponse != null)
            {
                _httpResponse.Dispose();
            }
            throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
        }
   }

但是,如果状态码为 400,则ErrorModel正在构建 的实例:

if ((int)_statusCode == 404)
{
    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
    try
    {
        _result.Body = SafeJsonConvert.DeserializeObject<ErrorModel>(_responseContent, DeserializationSettings);
    }
    catch (JsonException ex)
    {
        _httpRequest.Dispose();
        if (_httpResponse != null)
        {
            _httpResponse.Dispose();
        }
        throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
    }
}

因此,每当我使用此方法时,我都必须检查返回的对象的类型,以确定我是否有UserModel一个ErrorModel.

当我调用自动生成的客户端时,我必须这样做:

object result = await client.GetUserAsync(tenantId, departmentId);

switch (result)
{
    case List<UserModel> userModels:
        // Handle the users.
    case ErrorModel errorModel:
        // Handle the error.
}

这会在运行时而不是编译时推动任何类型安全检查,这反过来又会导致错误。

问题

如何在 C# 中处理这种情况而不必依赖运行时类型检查?

4

0 回答 0