我有一个 Asp.Net Core 2.2 Web api项目。最近,我尝试通过添加DataAnnotation或FluentValidation库来添加模型验证。
在我的单元测试中,我可以看到即使传递无效的模型值,模型状态也是有效的。
启动.cs
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddFluentValidation();
services.AddTransient<IValidator<ClientDto>, ClientValidator>();
客户端控制器
我的控制器继承自 ControllerBase 并具有 [ApiController] 属性。
[HttpPost]
public async Task<IActionResult> Create([FromBody] ClientDto client)
{
if (!ModelState.IsValid)
return BadRequest();
await _clientsService.Create(client);
var clientAdded = await _clientsService.GetCustomer(c => c.IntegralFileName == client.IntegralFileName);
return CreatedAtAction("Create", client, clientAdded);
}
ClientDto.cs
public class ClientDto
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Admin { get; set; }
public bool Active { get; set; }
}
ClienValidator.cs
public class ClientValidator : AbstractValidator<ClientDto>
{
public ClientValidator()
{
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.FirstName).Length(4, 20);
RuleFor(x => x.LastName).Length(3, 20);
}
}
我想我尝试了一切,其中一些:
1(删除了 Fluent 验证并将其替换为数据注释
2(将 AddMcv 替换为
services.AddMvcCore()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonFormatters()
.AddApiExplorer()
.AddAuthorization()
.AddDataAnnotations()
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ClientValidator>());
但是我看不到模型状态值有任何差异。有什么想法吗??
谢谢
在单元测试期间,模型状态验证不会发生(或者说模型绑定不会发生是正确的(。本文介绍了一些实现所需内容的方法
尝试向 Dto 添加属性:
[Validator(typeof(ClientValidator))]
public class ClientDto