使用数据注释的无效日期异常
Exception with invalid dates using data annotations
有一个 Json API 模型,日期 属性 定义为:
[Required]
[DataType(DataType.Date, ErrorMessage = "Invalid expiry date")]
public DateTime ExpiryDate { get; set; }
发布错误的 ExpiryDate 值时,示例:
"ExpiryDate":"2020-02-31T00:00:00",
"ExpiryDate":"2020-01-99T00:00:00",
"ExpiryDate":"abc",
ModelState.Values.Errors[0].ErrorMessage 为空。相反,有一个模型异常,我不能 return 给 API 消费者,看起来很难看。
ModelState.Values.Errors[0].Exception = {"Could not convert string to DateTime: 2020-02-31T00:00:00. Path 'CardDetails.ExpiryDate', line 13, position 39."}
我的问题是:如何使数据注释生成错误而不是异常?为什么当前数据注释没有给出错误,这不是 [DataType(DataType.Date...] 的工作吗?
您应该创建自定义数据注释:
public class RequiredDateTimeAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
// Here your code to check date in value
}
}
这里的主要问题是 JSON 中的 DateTime 值(至少根据 JSON 解析器)具有特定格式,不遵循该格式是解析错误,即目前正在发生什么。
我认为您必须将值作为字符串输入并在其上进行转换和验证。有几个选择。一个是像 @erikscandola 提到的自定义 ValidationAttribute。另一个是在你的模型上实现 IValidatableObject 接口。
您还可以将模型 属性 转换为字符串,然后简单地在控制器操作中进行检查:
DateTime expiryDate;
if (!DateTime.TryParse(model.ExpiryDate, out expiryDate))
{
ModelState.AddModelError("", string.Format(
"The given ExpiryDate '{0}' was not valid", model.ExpiryDate));
}
该方法取决于您需要多少重用验证逻辑。
有一个 Json API 模型,日期 属性 定义为:
[Required]
[DataType(DataType.Date, ErrorMessage = "Invalid expiry date")]
public DateTime ExpiryDate { get; set; }
发布错误的 ExpiryDate 值时,示例:
"ExpiryDate":"2020-02-31T00:00:00",
"ExpiryDate":"2020-01-99T00:00:00",
"ExpiryDate":"abc",
ModelState.Values.Errors[0].ErrorMessage 为空。相反,有一个模型异常,我不能 return 给 API 消费者,看起来很难看。
ModelState.Values.Errors[0].Exception = {"Could not convert string to DateTime: 2020-02-31T00:00:00. Path 'CardDetails.ExpiryDate', line 13, position 39."}
我的问题是:如何使数据注释生成错误而不是异常?为什么当前数据注释没有给出错误,这不是 [DataType(DataType.Date...] 的工作吗?
您应该创建自定义数据注释:
public class RequiredDateTimeAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
// Here your code to check date in value
}
}
这里的主要问题是 JSON 中的 DateTime 值(至少根据 JSON 解析器)具有特定格式,不遵循该格式是解析错误,即目前正在发生什么。
我认为您必须将值作为字符串输入并在其上进行转换和验证。有几个选择。一个是像 @erikscandola 提到的自定义 ValidationAttribute。另一个是在你的模型上实现 IValidatableObject 接口。
您还可以将模型 属性 转换为字符串,然后简单地在控制器操作中进行检查:
DateTime expiryDate;
if (!DateTime.TryParse(model.ExpiryDate, out expiryDate))
{
ModelState.AddModelError("", string.Format(
"The given ExpiryDate '{0}' was not valid", model.ExpiryDate));
}
该方法取决于您需要多少重用验证逻辑。