gpt4 book ai didi

c# - 使用数据注释验证时不进入 Controller

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:20 24 4
gpt4 key购买 nike

我正在使用 ASP.NET Core restful web API。我的问题是我的 Controller 内部有一个服务器验证来检查 View 模型 (Contact.cs) 验证。

然而,当我在 Controller 中测试我的 POST 操作 CreateContact 时,该操作从未被输入,但根据我在 Contact.cs 类。

我不明白为什么要在进入 Controller 之前进行验证。我认为,在 Web API 中,将根据 ModelStateController 中检查服务器验证。然后我的 ModelState.IsValid 检查似乎没用了。

我的 View 模型:

public class Contact
{
[Required]
public int? Id { get; set; }
[MaxLength(20)]
public string FirstName { get; set; }
// ...
}

从未输入的我的 Controller 操作的一部分。

[Route("api/[controller]")]
[ApiController]
public class ContactsController : ControllerBase
{
[HttpPost]
public IActionResult CreateContact(ViewModels.Contacts.Contact contact)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

// ...
}
}

最佳答案

ApiController attribute你已经应用到你的 Controller 带有某些约定。其中之一是传递的模型在输入 Controller 操作之前自动验证。

因此,这有效地消除了在每个方法中检查 ModelState.IsValid 的需要。

您可以阅读有关 ApiController 属性的更多信息 in the official documentationin this blog post这两者也涵盖了该属性包含的其他约定。

如果您不想要这种行为,但仍希望能够在您的 Controller 操作中手动执行此操作,请查看 this question on disabling the functionality .

关于c# - 使用数据注释验证时不进入 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52535351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com