为什么 属性 在类型转换错误时得到验证?

Why property got validate when type conversion error?

我在 ASP.NET Web API 中遇到模型验证问题。这是一个有问题的模型:

public sealed class AccessTokenRequest
{
    [Required]
    public Guid GameId { get; set; }

    [Required]
    public string GameAccessToken { get; set; }

    [Range(0, int.MaxValue)]
    public int? Lifetime { get; set; }
}

当我为 GameId 传递一个无法转换为 Guid 的字符串时,这是 return 两个验证错误。一个是:

The value 'xxxxxxxxxxxxxxx' is not valid for GameId.

另一个是:

The value is required.

我只想要第一个return。后者没有意义,因为已经提供了值。

提前致谢。

老实说,我不确定如果不创建自定义验证属性是否可行。

问题是提供了无效的 GUID,因为它无法被正确解析,所以它给出了 null 作为结果。活页夹尝试将 null 分配给具有 [Required] 属性的 属性,因此会出现 The value is required. 错误。

让我们来看看 [Required] 属性:

public override bool IsValid(object value)
{
  if (value == null)
    return false;
  string str = value as string;
  if (str != null && !this.AllowEmptyStrings)
    return str.Trim().Length != 0;
  return true;
}

如您所见,检查了 null 值。

您可以从头开始编写新属性,也可以从 RequiredAttribute 派生并覆盖 IsValid 方法。