c# - 验证并将 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,因为它说有效。你能告诉我我错过了什么吗?
解决方案
推荐阅读
- quantum-computing - 为什么量子计算机中的恒定运算需要第二个 qbit?
- c++ - 如何擦除字符串中的第一个和最后一个字符?
- graphite - 石墨 - 计算包含多个值的两个系列的差异
- node.js - 在 Mongodb 的数组中删除元素 null
- excel - Excel,如何制作一个for循环?
- vba - 访问VBA过滤出多个标准一个表标记完成时完成
- image - 尝试从图库中选择图像并使用相机抖动拍摄图像时出现 setState() 或 markNeedsBuild() 错误
- r - 关于在 R 中使用 ggplot2 获得正确的轴标题
- python - 如何使用 yFinance 在 5 天内每隔 4 小时下载一次数据?
- amazon-web-services - 为什么我的 AWS CloudWatch 警报没有被触发?