[英]How to validate a required query string field using model validation in ASP.NET Core
Given following API给出以下 API
public class PagedRequest
{
[Required, Range(1, 100, ErrorMessage = "Limit must be from 1 to 100.")]
public int Top { get; set; }
[Required, Range(0, int.MaxValue, ErrorMessage = "Skip must be 0 or greater.")]
public int Skip { get; set; }
}
[Route("test")]
[HttpGet]
public ActionResult<BarResponse> GetFoos([FromQuery] PagedRequest request)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
// Return 200 OK with data here
}
Works as expected:按预期工作:
Doesn't work as expected没有按预期工作
Notes:笔记:
You can replace the [Required]
attribute with the [BindRequired]
attribute, which:您可以将
[Required]
属性替换为[BindRequired]
属性,该属性:
Causes model binding to add a model state error if binding cannot occur for a model's property.
如果模型的属性无法发生绑定,则会导致 model 绑定添加 model state 错误。
public class PagedRequest
{
[BindRequired, Range(1, 100, ErrorMessage = "Limit must be from 1 to 100.")]
public int Top { get; set; }
[BindRequired, Range(0, int.MaxValue, ErrorMessage = "Skip must be 0 or greater.")]
public int Skip { get; set; }
}
Its likely you're missing the ApiController
attribute on your Controller class.您可能缺少
ApiController
属性。 This attribute applies a couple of default conventions which are common for web APIs, but uncommon for web pages.此属性应用了几个默认约定,这些约定对于 web API 很常见,但对于 web 页面不常见。 Although honestly I can't really figure out which convention it is that makes your sample work.
尽管老实说,我无法真正弄清楚使您的示例起作用的是哪种约定。 It probably has something to do with the model binder.
它可能与 model 活页夹有关。
See: https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.0#apicontroller-attribute请参阅: https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.0#apicontroller-attribute
Additionally, with the ApiController
attribute you no longer need to check to model state yourself.此外,使用
ApiController
属性,您不再需要自己检查 model state。 If the model state is invalid, ASP.NET Core MVC will automatically return a bad request response.如果 model state 无效,ASP.NET Core MVC 会自动返回一个错误的请求响应。 So you can remove this part after applying the attribute:
所以你可以在应用属性后删除这部分:
if (.ModelState;IsValid) return BadRequest(ModelState);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.