ASP.NET Core-验证合同中仅指定一个参数
我有以下合同:
public class UpdateUserRequest
{
public string Id { get; set; }
public string Email { get; set; }
public string AccountId { get; set; }
}
我想验证只有一个更新三个的属性。我使用ivalidtableObject
来实现这一点:
public class UpdateUserRequest : IValidatableObject
{
public string Id { get; set; }
public string Email { get; set; }
public string AccountId { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if ((Id is null && Email is null && AccountId is null) ||
(Id is not null && Email is not null && AccountId is not null))
{
yield return new ValidationResult("Exactly one parameter must be specified.",
new[] { nameof(Id), nameof(Email), nameof(AccountId) });
}
}
}
在提供全部三个的情况下有效或 none 。但是,如果提供两个,该怎么办?是否有一种更简单的方法来实现仅提供一个参数的验证,而不是多个检查?
I have the following contract:
public class UpdateUserRequest
{
public string Id { get; set; }
public string Email { get; set; }
public string AccountId { get; set; }
}
I want to validate that only one update property of the three is set in this request. I used IValidtableObject
to achieve this:
public class UpdateUserRequest : IValidatableObject
{
public string Id { get; set; }
public string Email { get; set; }
public string AccountId { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if ((Id is null && Email is null && AccountId is null) ||
(Id is not null && Email is not null && AccountId is not null))
{
yield return new ValidationResult("Exactly one parameter must be specified.",
new[] { nameof(Id), nameof(Email), nameof(AccountId) });
}
}
}
That works in stopping cases where all three are supplied or none. But what do I do if two are supplied? Is there an easier way to achieve validation that only one parameter is supplied, instead of multiple if
checks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的方法是对它们进行计数:
您可以使用一种实用程序方法概括它,该方法使用反射来枚举请求对象上的属性并返回非默认属性的计数,但似乎有些沉重。
Simplest way is to just count them:
You could generalise it with a utility method that uses reflection to enumerate the properties on the request object and returns a count of non-default properties, but seems a little heavy handed.