【问题标题】:ModelState is always valid in ASP.NET.CORE 2.2 Web ApiModelState 在 ASP.NET.CORE 2.2 Web Api 中始终有效
【发布时间】: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


【解决方案1】:

尝试将属性添加到您的 Dto:

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

【讨论】:

【解决方案2】:

在单元测试期间没有发生模型状态验证(或者说没有发生模型绑定是正确的)。 This article 描述了一些实现你想要的方法

【讨论】:

  • 首先这篇文章很棒并且很欣赏它。但是即使在正常调试中模型状态也是有效的,可能会以一种奇怪的方式发现问题,但后来我检查了邮递员,模型状态仍然是始终有效。
  • 嗯,这很奇怪。尝试根据您问题中的代码重现您的问题 - 验证按预期工作。 client Create 方法中的参数是否已全部传递值?你能出示这位邮递员的请求正文吗
  • 在我的职业生涯中又一次,这个问题在不知道为什么的情况下得到了解决。清理,重建更新 nuget 包,使验证正常工作,
猜你喜欢
  • 2011-02-09
  • 2011-12-31
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
  • 2016-02-06
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
相关资源
最近更新 更多