文章出處

在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


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()