我正在构建一个自定义JsonConverter,以便在模型类的属性中使用。该模型用作Web控制器中的输入参数。在我的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,即使我得到了一个糟糕的配角。
如何让控制器看到转换器抛出异常,以便返回适当的响应?
发布于 2016-07-27 06:34:08
您必须检查模型状态错误,这将包含模型的验证错误和其他属性错误。因此,您可以在代码中执行这样的操作:
[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();
}https://stackoverflow.com/questions/38602438
复制相似问题