I have an Asp.Net Core 2.2 web api project.Recently i tried to add validation on the models by adding DataAnnotation or the FluentValidation library.
In my Unit tests though i can see that even passing invalid model values the model state is valid.
StartUp.cs
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddFluentValidation();
services.AddTransient<IValidator<ClientDto>, ClientValidator>();
ClientController
My Controller inherits from the ControllerBase and has the [ApiController] attribute.
[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);
}
}
I think i tried everything , some of them:
1)Removed Fluent Validation and replace it with DataAnnotations
2)Replace AddMcv with
services.AddMvcCore()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonFormatters()
.AddApiExplorer()
.AddAuthorization()
.AddDataAnnotations()
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ClientValidator>());
But i cant see any difference in the ModelState value. Any Ideas??
Thanks
Model state validation is not happening (or it's right to say that model binding does not happening) during unit-testing. This article describes some ways to implement what you want
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With