如何解决MinLengthAttribute 是否也适用于字典?
我有一个 .Net Core 3.1 应用程序,想确保字典至少包含一对。文档说数据注释 MinLength
适用于字符串和数组
[MinLength(1)]
public Dictionary<T,V> MyDictionary { get; set; }
我是否必须创建自己的验证属性,或者上面的代码是否适用于字典?
我通过创建一个 Web API 项目并修改示例控制器做了一个小测试
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public ActionResult<TheQueryFields> Get([FromQuery] TheQueryFields theQueryFields)
{
return Ok(theQueryFields);
}
}
public class TheQueryFields
{
[MinLength(1)]
public Dictionary<string,string> Collection { get; set; }
}
使用 https://localhost:44306/weatherforecast
调用此端点不会返回 400,验证通过。
所以对于字典,我似乎必须创建自己的验证属性?
解决方法
MinLenghAttribute
,在装饰字段中检查 Length
属性(在 string
或 Array
的情况下)或 Count
属性({ {1}}、Dictionary
和其他集合)。
您可以在此处查看参考源实现:MinLengthAttribute
然而,正如评论中@41686d6564 所指出的,如果您传递一个 List
值,这个验证器会忽略,并且只返回 null
。
因此,更简单的方法是将 True
与 MinLenghAttribute
一起使用。
RequiredAttribute
另一方面,实现自定义验证器非常简单。这是一个验证集合不为空或为空的示例:
[Required,MinLengh(1)]
public Dictionary<T,V> MyDictionary { get; set; }
你可以这样使用它:
// NotEmpty validates that a collection or string is not null or empty.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public sealed class NotEmptyAttribute : ValidationAttribute {
const string ValidationError = "The field {0} must be a non-empty collection.";
public NotEmptyAttribute() : base(ValidationError) { }
public override bool IsValid(object value) => value is IEnumerable e && e.Cast<object>().Any();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。