ModelState在ASP.NET.CORE 2.2 Web Api中始终有效

时间:2019-06-10 14:48:17

标签: c# .net-core asp.net-core-webapi

我有一个Asp.Net Core 2.2 Web api项目。最近,我尝试通过添加DataAnnotation或FluentValidation库在模型上添加验证。

尽管在单元测试中,我可以看到即使传递无效的模型值,模型状态也是有效的。

StartUp.cs

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
        .AddFluentValidation();

services.AddTransient<IValidator<ClientDto>, ClientValidator>();

ClientController

我的控制器继承自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验证,并将其替换为DataAnnotations

2)将AddMcv替换为

   services.AddMvcCore()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonFormatters()
            .AddApiExplorer()
            .AddAuthorization()
            .AddDataAnnotations()
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ClientValidator>());

但是我看不到ModelState值的任何区别。 有什么想法吗?

谢谢

2 个答案:

答案 0 :(得分:1)

在单元测试期间,没有发生模型状态验证(或者可以说没有发生模型绑定)。 This article介绍了一些实现所需内容的方法

答案 1 :(得分:0)

尝试将属性添加到Dto:

[Validator(typeof(ClientValidator))]
public class ClientDto