首页 > 解决方案 > 验证并将 ModelState 从服务层传递到控制器 WebAPI

问题描述

我按照以下链接在服务层完成验证 https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/validating-with-a-服务层-cs

我最终有循环依赖。所以去掉validation/ModelStateWrapper的依赖注入,使用Initialize static方式。

关于项目的简要说明:我有 API、服务层、存储库、数据库。我正在使用 Automapper 将 DTO 映射到实体。控制器:

public StudentController(IStudentService studentService, IMapper mapper)
        {
            _studentService = studentService;
            _studentService.Initialize(new ModelStateWrapper(this.ModelState));
            _mapper = mapper;
        } 

    public IActionResult CreateStudent([FromBody] StudentCreationDto student)
            {    
                if (student== null)
                {
                    return BadRequest();
                }                         
                if (!ModelState.IsValid)
                {
                    return new UnprocessableEntityObjectResult(ModelState);
                }
                var studentEnitty = _mapper.Map<Student>(student);
                var createSuccessful = _studentService.CreateStudent(studentEnitty);
                if (!createSuccessful)
                {                
                    return new UnprocessableEntityObjectResult(ModelState);
                }  
            }

服务:

public void Initialize(IValidationDictionary validationDictionary)
                {
                    _validationDictionary = validationDictionary;
                }

public bool CreateStudent(Student student)
            {
                //Check if Student already exists
                if (!ValidateStudentToCreate(student))
                {                
                    return false;
                }

                //Create Portal 
                var createSuccessful = _studentRepository.CreateStudent(student);
                if (!createSuccessful)
                {
                    return false;
                }
                return true;
            }

    private bool ValidateStudentToCreate(Student student)
    {
        //throw new Exception();            
        if (_studentRepository.StudentEmailExists(student.Email))
        {
            _validationDictionary.AddError("Email", "Student already exists");
        }             

        bool isValid = _validationDictionary.IsValid;
        return isValid;
    }

我有带有 AddError 和 IsValid 的 IValidation 字典。ModelStateWrapper 实现 IValidationDictionary。

验证字典

public interface IValidationDictionary
    {
        void AddError(string key, string errorMessage);
        bool IsValid { get; }
    }

模型状态包装器

public class ModelStateWrapper : IValidationDictionary
    {       

        private ModelStateDictionary _modelState;

        public ModelStateWrapper(ModelStateDictionary modelState)
        {
            _modelState = modelState;
        }

        #region IValidationDictionary Members


        public void AddError(string key, string errorMessage)
        {
            _modelState.AddModelError(key, errorMessage);
        }          

        public bool IsValid
        {
            get { return _modelState.IsValid; }
        }

我正在尝试在控制器级别获取数据模型验证,并且诸如学生之类的业务逻辑存在于服务级别。我能够执行验证,但是,我无法将模型状态返回给 Controller,因为它说有效。你能告诉我我错过了什么吗?

标签: c#asp.net-mvcasp.net-coreasp.net-web-apidesign-patterns

解决方案


推荐阅读