【发布时间】:2019-10-24 23:42:54
【问题描述】:
我有一个 Asp.Net Core 2.2 web api 项目。最近我尝试通过添加 DataAnnotation 或 FluentValidation 库来在模型上添加验证。
在我的单元测试中,虽然我可以看到即使传递无效的模型值,模型状态也是有效的。
StartUp.cs
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddFluentValidation();
services.AddTransient<IValidator<ClientDto>, ClientValidator>();
客户端控制器
我的 Controller 继承自 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; }
}
客户端验证器.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 Validation 并用 DataAnnotations 替换它
2) 将 AddMcv 替换为
services.AddMvcCore()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonFormatters()
.AddApiExplorer()
.AddAuthorization()
.AddDataAnnotations()
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ClientValidator>());
但我看不出 ModelState 值有什么不同。 有什么想法吗??
谢谢
【问题讨论】:
-
看看你的实际测试会很有帮助。您已将其称为单元测试,如果确实如此,那么验证将永远起作用,因为这只会作为模型绑定过程的一部分发生,没有它就不会运行其余的 ASP.NET Core 机器。要对此进行测试,您需要使用测试服务器进行集成测试。
标签: c# .net-core asp.net-core-webapi