2016-07-27 34 views
2

我正在構建一個自定義的JsonConverter以在模型類的屬性中使用。該模型用作Web API控制器中的輸入參數。在我的JsonConverter中,如果我不喜歡輸入,我會丟棄FormatException如何捕獲JsonConverter屬性中引發的異常?

這裏是我的模型的一部分:

public class PropertyVM 
{ 
    public string PropertyId { get; set; } 

    [JsonConverter(typeof(BoolConverter))] 
    public bool IsIncludedInSearch { get; set; } 
} 

這是我的控制器操作:

[HttpPost, Route("{propertyId}")] 
public IHttpActionResult UpdateProperty(string propertyId, [FromBody] PropertyVM property) 
{ 
    bool success; 
    try 
    { 
     property.PropertyId = propertyId; 
     success = _inventoryDAL.UpdateProperty(property); 
    } 
    catch (Exception ex) when 
    ( 
      ex is ArgumentException 
     || ex is ArgumentNullException 
     || ex is ArgumentOutOfRangeException 
     || ex is FormatException 
     || ex is NullReferenceException 
     || ex is OverflowException 
    ) 
    { 
     return BadRequest(ex.Message); 
    } 

    if (!success) 
    { 
     return NotFound(); 
    } 

    return Ok(); 
} 

如果我打電話與IsIncludedInSearch壞值時,控制器,我希望趕在FormatException我控制器,但沒有發生。在我的轉換器中引發異常,但是在媒體格式化程序運行時會發生這種情況。當我進入我的控制器時,異常已經被拋出,但我無法捕捉到它。所以即使我得到了一個糟糕的參數,我也會返回OK

如何讓我的控制器看到轉換器引發異常,以便我可以返回相應的響應?

回答

1

您必須檢查將包含模型的驗證錯誤和其他屬性錯誤的模型狀態錯誤。所以你可以在你的代碼中這樣做:

[HttpPost, Route("{propertyId}")] 
    public IHttpActionResult UpdateProperty(string propertyId, 
     [FromBody] PropertyVM property) 
    { 
     bool success = false; 
     if (ModelState.IsValid) 
     { 
      try 
      { 
       property.PropertyId = propertyId; 
       success = _inventoryDAL.UpdateProperty(property); 
      } 
      catch (Exception ex) //business exception errors 
      { 
       return BadRequest(ex.Message); 
      } 

     } 
     else 
     { 
      var errors = ModelState.Select(x => x.Value.Errors) 
            .Where(y => y.Count > 0) 
            .ToList(); 
      return ResponseMessage(
       Request.CreateResponse(HttpStatusCode.BadRequest, errors)); 
     } 

     if (!success) 
     { 
      return NotFound(); 
     } 

     return Ok(); 
    } 
+0

完美,謝謝! – Val