【问题标题】:How to catch an exception thrown in a JsonConverter attribute?如何捕获 JsonConverter 属性中引发的异常?
【发布时间】: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


    【解决方案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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      • 2011-06-19
      • 2012-03-14
      相关资源
      最近更新 更多