如何让控制器的ModelState在服务中进行验证

本文关键字:服务 验证 ModelState 控制器 | 更新日期: 2023-09-27 18:11:54

我正是在这种情况下,这个人(控制器ModelState与modelstatewrapper)是除了我使用城堡温莎DI。在将模型保存到数据存储之前,我试图在服务中验证模型的业务逻辑端。如果验证失败,我希望得到模型状态错误并显示在我的视图中。(我将本文作为实现服务验证的指南:http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs)

下面是我的示例代码,
//My controller code
        public class TimeEntryController : TempoBaseController
        {
            public TimeEntryController(TimeService service, UserService userService)
            {
                _service = service;
                _userService = userService;
            }
            [Authorize(Roles = "Worker")]
            public ActionResult Index() 
            {
            return View();
            }
            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Index(EntryLogDto entry)
            {
              if(_service.AddEntryLog(entry))
              {
                return ViewSuccess();
              }else
              {
                return ViewFailue();
              }
            }
        }
//My Service class
    public class TimeService : GenericService
    {
        public TimeService(IRepository repository, IValidationDictionary validationDictionary, UserManager<ApplicationUser>     userManager)
            : base(repository, validationDictionary, userManager)
        {
        }
        public bool AddEntryLog(EntryLogDto log)
        {
            if (!ValidateEntryLog(log))
              {
                //return false;
            }
            else
            {
                //insert entry into database and return true
            }
            }
        protected bool ValidateEntryLog(EntryLogDto log)
        {
            //Check if the entry overlaps with any other entries
            bool res = _repository.Find<EntryLogDto>(//my linq logic);
            if (res)
            {
              _validationDictionary.IsValid = true;
            }else
            {
            _validatonDictionary.AddError("Entry", "Entry Overlaps.");
              _validationDictionary.IsValid = false;
            }
            return _validationDictionary.IsValid;
        }
    }
//Validation class
    public class TempoValidation : IValidationDictionary
    {
        private ModelStateDictionary _modelState;
        public TempoValidation(ModelStateDictionary modelState) // Issue is how am I gona give it this as the ModelStateDictiona         ry is controller specific
        {
            _modelState = modelState;
        }
        public void AddError(string key, string error)
        {
            _modelState.AddModelError(key, error);
        }
        public bool IsValid
        {
            get { return _modelState.IsValid; }
        }
    }
//Global.asax castle compnonent registration method
                container
                .Register(Component
                            .For<Tempo.Model.Configuration.TempoDbContext>()
                            .LifestylePerWebRequest()
                            .DependsOn(new { connectionString }))
                .Register(Component
                            .For<DbRepositories.ITempoDataContextFactory>()
                            .AsFactory())
                .Register(Component
                            .For<IRepository>()
                            .ImplementedBy<Tempo.Repositories.EntityFrameworkRepository.Repository>())
                .Register(Component
                            .For<TimeService>().LifestyleTransient())

我在我的服务类中注入IValidationDictionary,在那里我根据验证结果设置模型状态。当我使用控制器时,是否有一种方法可以传递控制器的模型状态?我不知道如何处理这个问题,我有许多控制器,我不知道我将如何/何时将通过各自的控制器的模型状态(如果可能的话,我想通过DI做到这一点)……我不知道城堡是否可以为每个控制器创建一个单独的TempoValidation类实例??

如何让控制器的ModelState在服务中进行验证

我知道这在默认情况下是不可能做到的,但是您可以使用Fluent Validation来实现这一点。

的例子:

ViewModel

 [Validator(typeof(VmSysTestValidator))]
    public class VmSysTestModel
    {
        public int Id { get; set; }
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
    }

流畅验证实现:

 public class VmSysTestValidator : AbstractValidator<VmSysTestModel>
    {
        public VmSysTestValidator()
        {
            RuleFor(x => x.FirstName).NotNull().WithMessage("First name is required");
            RuleFor(x => x.LastName).NotNull().WithMessage("Last Name is required");
        }
    }

控制器或业务逻辑端:

[HttpPost]
        public ActionResult TestPost(VmSysTestModel obj)
        {
            //Start Validation     From start to end you can call this code everywhere you want  , this will work like server side valdiatin
            //Instead of ModelState.IsValid you will call your fluent validator
            var testValidator = new VmSysTestValidator();
            var validationResult = testValidator.Validate(obj);
            if (validationResult.IsValid)
            {
            }
            else
            {
            }
            //End valdiation 
        }