【发布时间】:2016-07-27 01:51:05
【问题描述】:
我正在构建一个自定义 JsonConverter 以在模型类的属性中使用。该模型用作 Web API 控制器中的输入参数。在我的 JsonConverter 中,如果我不喜欢输入,我会抛出 FormatException。
这是我的模型的一部分:
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,即使我有一个错误的参数。
如何让我的控制器看到转换器引发了异常,以便我可以返回适当的响应?
【问题讨论】:
标签: c# json.net asp.net-web-api2