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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM