【问题标题】:consuming REST service, method returning multiple types .. what to do使用 REST 服务,方法返回多种类型.. 怎么办
【发布时间】:2015-06-08 08:40:15
【问题描述】:

我正在为我的应用使用其他人的 REST 服务。问题是每个请求在响应时可以返回 3 种不同类型中的 1 种 要么:

  1. 预期的成功响应类型
  2. 包装 500 (Error) 的错误响应
  3. 验证错误响应 (ValidationErrors)

我目前正在使用这样的类调用包装每个请求的服务:

public class ApiResponse<T>
{
    public T ResponseObject { get; set; }
    public ValidationErrors<ValidationError> Errors { get; set; }
    public Error Error { get; set; }
}



 public async Task<ApiResponse<AMethodResponse>> AMethod(AMethodRequest req)
    {
        ApiResponse<AMethodResponse> resp = new ApiResponse<AMethodResponse> { Errors = new ValidationErrors<ValidationError>() };
        using (HttpClient client = HttpClientFactory.Create(new AuthorisationHandler(), new ContentTypeHandler()))
        {
            client.BaseAddress = new Uri(BaseURI);

            var httpResponseMessage = await client.PostAsXmlAsync<AMethodRequest>("AMethod/", req);
            if (!httpResponseMessage.IsSuccessStatusCode)
            {
//its at this point that I need to work out if i am getting Validation Errors or.. a plain Error
//I can do this, but of course if its a plain error it will fall over
                resp.Errors = await httpResponseMessage.Content.ReadAsAsync<ValidationErrors<ValidationError>>();
            }
            else
            {
                resp.ResponseObject = await httpResponseMessage.Content.ReadAsAsync<AMethodResponse>();
            }
        }
        return resp;
    }

我想知道是否有更可靠的模式来编写消费方法。

谢谢

【问题讨论】:

  • REST 服务是否为每种可能性提供不同的状态代码?看起来它给出了 500 的错误,但它是否给出了 200 成功 验证错误?如果是这样,您可以直接使用httpResponseMessage.StatusCode(而不是简单的IsSuccessStatusCode)。如果在这两种情况下都是 200(REST 服务中的错误!),那么您可以使用 ReadAsStringAsync() 然后让您的代码检查序列化字符串以检查它是否是验证错误,然后在知道类型后手动反序列化。跨度>
  • 嗨,谢谢你的回复,完全没有想到。是的,它给出了 200 分,一切都很好。 400 表示验证错误,500 表示真正的错误。我会重新调整它。出于兴趣,代码看起来是否正确(忽略问题所在)
  • 也许我在这里的回答会有所帮助:stackoverflow.com/questions/30370604/get-calls-to-webapi/…

标签: asp.net-mvc rest asp.net-web-api


【解决方案1】:

它给出了 200 分,一切都很好。 400 表示验证错误,500 表示真正的错误

直接查看状态码,而不是使用IsSuccessStatusCode

var httpResponseMessage = await client.PostAsXmlAsync<AMethodRequest>("AMethod/", req);

switch (httpResponseMessage.StatusCode)
{
    case HttpStatusCode.OK:  //200
        resp.ResponseObject = await httpResponseMessage.Content.ReadAsAsync<AMethodResponse>();
        break;

    case HttpStatusCode.BadRequest:  //400
        resp.Errors = await httpResponseMessage.Content.ReadAsAsync<ValidationErrors<ValidationError>>();
        break;

    case HttpStatusCode.InternalServerError:  //500
        throw new Exception("failed");  // use appropriate exception and/or read 500 wrapper
        break;
}

return resp;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多