HttpClient读取ASP.NET Web API错误信息的简单方法
在C#中,用HttpClient调用Web API并且通过Content.ReadAsStringAsync()读取响应内容时,如果出现500错误(InternalServerError),会得到一个包含错误信息的json字符串:
{ "Message":"An error has occurred.", "ExceptionMessage":"", "ExceptionType":"", "StackTrace":"", "InnerException": { "Message":"", "ExceptionMessage":"", "ExceptionType":", "StackTrace":"", "InnerException": { "Message":"", "ExceptionMessage":"", "ExceptionType":"", "StackTrace":"" } } }
这样一个复杂的字符串可读性很差,通常只需要部分信息(比如ExceptionMessage)就可以知道错误的情况。
那如何读取所需的部分信息呢?
开始用的是 Microsoft.AspNet.WebApi.Client + dynamic,实现代码如下:
var response = await _httClient.GetAsync(url); dynamic content = await response.Content.ReadAsAsync<ExpandoObject>(); Console.WriteLine(content.ExceptionMessage);
后来一想,这个json字符串也是某种类型的实例序列化出来的,找到这个类型,然后直接反序列化这个类型的实例,岂不更简单。
找了找,发现原来就是Microsoft.AspNet.WebApi.Core中的HttpError:
namespace System.Web.Http { [XmlRoot("Error")] public sealed class HttpError : Dictionary<string, object>, IXmlSerializable { public HttpError(); public HttpError(string message); public HttpError(ModelStateDictionary modelState, bool includeErrorDetail); public HttpError(Exception exception, bool includeErrorDetail); public string ExceptionMessage { get; set; } public string ExceptionType { get; set; } public HttpError InnerException { get; } public string Message { get; set; } public string MessageDetail { get; set; } public HttpError ModelState { get; } public string StackTrace { get; set; } public TValue GetPropertyValue<TValue>(string key); } }
于是改用下面更简单的实现代码:
var response = await _httClient.GetAsync(url); Console.WriteLine((await response.Content.ReadAsAsync<HttpError>()).ExceptionMessage);
注:需要nuget安装Microsoft.AspNet.WebApi.Client与Microsoft.AspNet.WebApi.Core