C# 模型验证,涉及对被验证实体采取的行动
我们如何根据对特定实体采取的行动来验证数据?对于数据注释模型验证,还有哪些更高级的替代方案?可能可插入Asp.net MVC和WebAPI,因此验证仍在自动进行 例子 假设一个web应用程序的用户加入表单C# 模型验证,涉及对被验证实体采取的行动,c#,asp.net-mvc,validation,asp.net-web-api,data-annotations,C#,Asp.net Mvc,Validation,Asp.net Web Api,Data Annotations,我们如何根据对特定实体采取的行动来验证数据?对于数据注释模型验证,还有哪些更高级的替代方案?可能可插入Asp.net MVC和WebAPI,因此验证仍在自动进行 例子 假设一个web应用程序的用户加入表单 public class User { // required when providing user as input // not provided when creating new instance public int Id { get; set; }
public class User
{
// required when providing user as input
// not provided when creating new instance
public int Id { get; set; }
// required when user joins and of specific format AND IS UNIQUE based on data store users
// optional when providing user as input
public string Email { get; set; }
...
}
也许对象继承会有所帮助,但正如我所想,继承只是一种黑客行为。基类几乎没有任何属性,我们最终可能会得到几个非常相似的(属性)类,但使用不同的注释只是为了使用数据注释。这可不好
期望的实现
我在考虑根据对特定实体采取的行动进行验证。所以我们可以定义如下:
public class User
{
[Required(Action = ValidationAction.Provide)] // or whatever action we'd define
public int Id { get; set; }
[Required(Action = ValidationAction.Create)]
[IsUnique(Action = ValidationAction.Create)] // custom DataAnnotations validator
[EmailAddress]
public string Email { get; set; }
...
}
Asp.net MVC和WebAPI控制器操作将需要某种属性来提供有关特定实体和参数的操作信息
[HttpPost]
[ValidateForAction("user", ValidationAction.Create)]
[ValidateForAction("user.InvitedBy", ValidationAction.Provide)]
public ActionResult Join(User user)
{
...
}
或者为所有参数(及其子树中的对象实体)统一设置
当控制器上不存在validateFractionAttribute
时,操作验证应仅检查与验证操作无关的注释(如上文在我的实体示例中设置的EmailAddressAttribute
)
一个类似的例子可能是Stackoverflow场景,添加一个答案,其中发布的答案详细信息将通过创建操作进行验证,而相关的问题实体(答案中的属性)将根据提供操作进行验证,因为我们主要只需要它的Id
有这样的验证库吗?有人做过类似的事情吗?
您将如何进行此类验证?这听起来类似于requiredif验证器,其中验证依赖于另一个属性。但是,模型验证在这里不起作用,因为模型“应该”独立于视图或控制器 假设有一个视图模型与控制器上的各个动作关联,那么视图模型可以使用与视图要求一致的数据注释。有关MVVM模式的更多详细信息,请参阅 关于Id的最后一条注释。由于int的默认值是有效值,因此不确定所需属性是否有效。也许是正则表达式?([1-9]|[0-9]{2,10})
我想你必须在这里创建你自己的验证类。简单的回答是,你不应该。如果视图中有未使用的属性,则应为其创建新的ViewModel,该ViewModel仅包含所需的属性。在您的情况下,它将不包括电子邮件属性,因此没有什么需要验证的。
[HttpPost]
[ValidateForAction(ValidationAction.Create)]
public ActionResult Join(User user)
{
...
}
public class RegistrationController
[HttpPost]
public ActionResult Provide(UserProvideViewModel user)
{
...
}
[HttpPost]
public ActionResult Join(UserJoinViewModel user)
{
...
}
}
[MetadataType(typeof(UserProvideViewModel_Validation))]
public partial class UserProvideViewModel : User
{
// properties unique to the view model
}
public class UserProvideViewModel_Validation
{
[RegularExpression(@"^([1-9]|\d{2,10})$")]
public Id { get; set; }
}
[MetadataType(typeof(UserJoinViewModel_Validation))]
public partial class UserJoinViewModel : User
{
// properties unique to the view model
}
public class UserJoinViewModel_Validation
{
[Required]
[EmailAddress]
public Email { get; set; }
}