2017-05-29 6 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 
} 

自分のプロパティの値を得る方法はありますか?

答えて

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

グレート、そう

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

を次のように、すべてのカスタムプロパティをシリアル化するときに我々はその後、リフレクションを使用することができることを自動化するためには、出力につくれ。

関連する問題