【发布时间】:2018-07-10 20:27:11
【问题描述】:
我有两个扩展基本模型的不同模型。
public class basemodel
{
public string prename;
public string surname;
}
public class modelA : basemodel
{
public string street;
public int gender; //0 = m / 1 = f
}
public class modelB : basemodel
{
public string street;
}
现在我想在我的 HTTP PUT 控制器中验证它们。控制器根据用户的角色在modelA 或modelB 之间做出决定(管理员可以看到modelA,用户可以看到modelB)。
public ActionResult Put(MyDto myDto)
{
if (validationSrv.IsValid(myDto, ruleSetNames: "Edit", propertyNames: null))
{
session.Merge(myDto);
session.Flush();
session.Evict(myDto);
} //else xyz
}
我的实际验证器如下所示。
public MyValidator() : AbstractValidator<basemodel>
{
RuleSet("Edit", () =>
{
editBaseValidation();
});
}
private void editBaseValidation()
{
RuleFor(a => a.prename)
.NotEmpty()
.Length(5, 50);
RuleFor(a => a.surname)
.NotEmpty()
.Length(5, 50);
//say this is optional!
RuleFor(a => a.street)
.NotEmpty()
//say this is optional!
RuleFor(a => a.gender)
.NotEmpty()
}
现在我的问题。有没有办法让我的验证器说 street 或 gender 等某些属性是可选的,具体取决于所使用的模型?所以我只能对基本模型使用验证器,验证器决定验证或不验证哪些属性。
提前致谢:-)
【问题讨论】:
标签: c# validation nhibernate fluentvalidation