繁体   English   中英

WebApi无法序列化从Exception派生类声明的属性

[英]WebApi can't serialize attribute declared on derived class from Exception

调用Get api方法时,无法获取在BaseException上创建的属性值。 知道为什么吗?

public class BaseException : Exception
{
    public  string ExType { get; set; }

    public JObject Properties { get; set; }

    public Guid ErrorCodeId { get; set; }

    public BaseException(string message): base(message) { }
}

public class BadRequestException : BaseException
{
    public BadRequestException(string message) : base(message) { }
}

// GET: api/<controller>
public virtual IHttpActionResult Get()
{
    IHttpActionResult result = null;
    try
    {
        throw new Exception("Error description here");
        result = Ok();
    }
    catch (Exception ex)
    {
        result = ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, new BadRequestException(ex.Message)
        {
            ExType = "Any exception type"//Can't get this value in the output JSON
        }));
    }
    return result;
}

ExType值未显示。 我得到的结果如下:

{
  "ClassName": "BadRequestException",
  "Message": "Error description here",
  "Data": null,
  "InnerException": null,
  "HelpURL": null,
  "StackTraceString": null,
  "RemoteStackTraceString": null,
  "RemoteStackIndex": 0,
  "ExceptionMethod": null,
  "HResult": -2146233088,
  "Source": null,
  "WatsonBuckets": null
}

有什么方法可以获取我自己财产的抵押价值?

关于此答案, 那么使自定义.NET Exception可序列化的正确方法是什么?

序列化从Exception继承的自定义继承类的对象时,需要显式添加新属性。 为此,我们应该重写GetObjectData方法,并将要序列化的所有属性和值放入info中。

public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
    base.GetObjectData(info, context);
}

太好了,要自动化,我们可以按如下方式使用反射

public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
    //Getting first from base
    base.GetObjectData(info, context);

    if (info != null)
    {
        foreach (PropertyInfo property in this.GetType().GetProperties())
        {
            //Adding only properties that not already declared on Exception class
            if (property.DeclaringType.Name != typeof(Exception).Name)
            {
                info.AddValue(property.Name, property.GetValue(this));
            }
        }
    }
}

然后,在序列化所有自定义属性时,将出现在输出中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM