【发布时间】:2023-02-15 11:20:40
【问题描述】:
我使用 .NET 6 在 VS 2022 中创建了一个 WebAPI 项目
我用 [MaxLength(5)] 和 [MinLength(5)] 属性注释了模型的客户类 CustomerId 属性。
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
private readonly NorthwindContext _ctx;
// ...
[HttpPost]
public Customer Insert(Customer customer)
{
// Method never called. Somewhere the pipeline instantly
// sends the HTTP 400 response with the correct error message.
if (!ModelState.IsValid)
{
}
如果我使用无效数据调用 API,比如 4 或 6 长度的 CustomerId,则永远不会调用 Insert 方法。管道在某处立即发送 HTTP 400 响应正确的验证错误信息
问题
不清楚,那么 ModelState.IsValid 什么时候会为假?我可以配置管道以允许调用该方法吗?
【问题讨论】:
-
400 可能意味着请求根本无法解析为控制器操作/路由,您将发布到哪个目标 URL?
-
绝对不是这样。那将是 404。此外,如果我发出完全相同的请求但具有有效数据,则会调用该方法。我还在我的 OP 中写道,400 中的错误消息是正确的。
-
...但现在我编辑它以更正验证消息...更明确
-
这可能是您的路线,但如果没有任何客户端代码,很难说清楚。
标签: c# validation asp.net-core-webapi