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
。
如何讓我的控制器看到轉換器引發異常,以便我可以返回相應的響應?
完美,謝謝! – Val