如何验证未通过Post方法发送的数据?

时间:2019-07-04 13:54:29

标签: asp.net-mvc entity-framework

我在控制器中有一个静态对象,该对象将填写某些级别的注册表格。最后,我想通过modelstate方法验证此对象,但由于这不是通过post方法发送而无法实现的。验证方式。

public class AccountController : Controller
{
    private MyDb db = new MyDb();
    private static Trainer trainer = new Trainer();
    public Trainer InfoSave(Trainer info)
    {
        trainer.SchoolGrade = info.SchoolGrade;
        trainer.SchoolMajor = info.SchoolMajor;
        trainer.MajorId = info.Major.Id;
        trainer.History = info.History;
        trainer.Major = info.Major;
        if (ModelState.IsValid)
            return true;
        else
            return false;

}

1 个答案:

答案 0 :(得分:0)

您可以使用某些第三方库来松散耦合验证逻辑。我正在使用FluentValidation库。您可以利用它:

using FluentValidation;

public class TrainerValidator : AbstractValidator<Trainer> {
  public TrainerValidator() {
    RuleFor(c=> c.Name).NotNull().WithMessage("Name is required");
  }
}

public class AccountController : Controller
{
    private MyDb db = new MyDb();
    private static Trainer trainer = new Trainer();
    public Trainer InfoSave(Trainer info)
    {
        trainer.SchoolGrade = info.SchoolGrade;
        trainer.SchoolMajor = info.SchoolMajor;
        trainer.MajorId = info.Major.Id;
        trainer.History = info.History;
        trainer.Major = info.Major;
        TrainerValidator validator = new TrainerValidator();
        ValidationResult result = validator.Validate(trainer);
        if (result.IsValid)
            return true;
        else
            return false;

}

您可以根据需要扩展它。这是相同的FluentValidation

的链接