【发布时间】:2016-10-30 20:02:05
【问题描述】:
我正在尝试从可能存在或不存在的 HttpResponseMessage 消息中提取 HttpError。如果 Api 抛出异常,它将被序列化为 HttpError 但是诸如 404 之类的错误不会采用这种格式。
如果我们未能反序列化 HttpError,我已设法通过捕获引发的异常来修复以下代码中的此错误。
问题是我现在正在使用异常驱动的开发。
理想情况下,我想要这样的东西。
var httpError = await response.Content.TryReadAsAsync<HttpError>(formatters);
if (httpError == null)
{
// Definetly not an HttpError and no exception thrown
}
肯定是一种简单的方法来告诉 HttpContent 中的内容类型吗?
public static async Task<ApiResponseMessage<T>> GetApiResponseAsync<T>(this HttpResponseMessage response, IEnumerable<MediaTypeFormatter> formatters) where T : class
{
if (!response.IsSuccessStatusCode)
{
HttpError httpError;
// Exception driven programming
try
{
// Could use string?
var contentString = response.Content.ReadAsStringAsync();
// This doesn't work. Throws exception if not correct type
var contentObject = await response.Content.ReadAsAsync<object>();
var alwaysNull = contentObject as HttpError;
httpError = await response.Content.ReadAsAsync<HttpError>(formatters);
}
catch (Exception)
{
httpError = null;
}
return new ApiResponseMessage<T>
{
IsSuccess = false,
HttpError = httpError,
Response = response
};
}
return new ApiResponseMessage<T>
{
IsSuccess = true,
Result = await response.Content.ReadAsAsync<T>(formatters),
Response = response
};
}
【问题讨论】:
标签: c# asp.net asp.net-web-api casting asp.net-web-api2