zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    使用docker试用各种软件及docker-ES设置
    Atom读写MarkDown插件选择,以及墙内安装markdown-preview-enhanced,及markdown和mermaid使用教程
    杂谈迁移tomcat项目到docker,以及遇到的问题
    MongoSpark 28799错误
    MongoDB运维心得(一)
    Ubuntu16.04 appstreamcli错误
    MongoExport后的负载均衡问题查询及解决:can't accept new chunks because there are still 2 deletes from previous migration
    MongoDB集群单mongos的问题总结
    Linux上不了网的几个排查点
    git忽略某些文件的几种方法
  • 原文地址:https://www.cnblogs.com/dudu/p/4760425.html
Copyright © 2011-2022 走看看