我正在为我的应用程序使用别人的REST服务。问题是每个请求在响应时可以返回3种不同类型中的1种 要么:
Error
)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;
}
我想知道编写消费方法是否有更可靠的模式。
感谢
答案 0 :(得分: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;