2017-05-29 43 views
0

我無法獲取在調用Get api方法時在BaseException上創建的屬性值。任何想法爲什麼?WebApi無法序列化從派生類聲明的屬性異常

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 
} 

有什麼方法可以獲得我自己的屬性的serealized值?

回答

0

那麼關於這個答案What is the correct way to make a custom .NET Exception serializable?

在從Exception中序列化自定義繼承類的對象時,需要顯式添加新屬性。 要做到這一點,我們應該重寫GetObjectData方法,並將所有屬性和值放入信息中,以便序列化。

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

大,因此自動我們序列化所有自定義屬性的輸出apear時,按如下

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)); 
      } 
     } 
    } 
} 

然後可以使用反射。