简体   繁体   English

如何在 ASP.NET 核心中使用 model 验证来验证所需的查询字符串字段

[英]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:按预期工作:

  • test?skip=0&top=10 -> returns 200 test?skip=0&top=10 -> 返回 200
  • test?skip=0&top=0 -> returns BadRequest with error messages test?skip=0&top=0 -> 返回带有错误消息的 BadRequest

Doesn't work as expected没有按预期工作

  • test?top=0, returns 200 OK, expected required field validation error for Skip field. test?top=0,返回 200 OK,跳过字段的预期必填字段验证错误。

Notes:笔记:

  • Using ASP.NET Core 3.0使用 ASP.NET 内核 3.0
  • This used to work with FromUri in ASP.NET Framework 4.x, then I'ld use a non-parameterless constructor, which is no longer allowed这曾经在 ASP.NET Framework 4.x 中与 FromUri 一起使用,然后我将使用不再允许的非无参数构造函数

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.

相关问题 根据Model Asp.net Core API验证Json String - Validate Json String against Model asp.net core api ASP.NET Core 中必需的查询字符串参数 - Required query string parameter in ASP.NET Core 如何验证模型取决于使用ASP.NET Core Web API的布尔数据类型值 - How to validate model depends on bool datatype value using asp.net core web api Asp.net core 如何对视图组件进行模型验证 - Asp.net core how to do model validation on View Components ASP.NET核心 - 自定义模型验证 - ASP.NET Core - Custom model validation 字符串字段是必需的。 即使你在Asp.Net Core中没有Required属性? - The string field is required. even thou there is no Required attribute in Asp.Net Core? 如何使用 ASP.NET Core 更改输入字段的客户端验证错误 CSS 类? - How to alter the client-side validation error CSS class of an input field using ASP.NET Core? 如何使用 asp.net core 3.1/5 mvc 在 razor 视图中使用 * (基于 [Required] 注释)自动标记必填字段标签? - How can I automatically mark required field labels with a * (based on [Required] annotation) in a razor view using asp.net core 3.1/5 mvc? ASP.NET MVC 验证错误:<field> 字段为必填项 - ASP.NET MVC Validation error: The <field> field is required ASP.NET 核心 MVC model 在视图模型中验证与基础 model - ASP.NET Core MVC model validation in viewmodel with base model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM