c# - ASP Net Core 模型验证 Range 属性被忽略
问题描述
我正在使用 Microsoft.AspNetCore.Mvc 2.1.3。
在Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services
.AddSingleton<ILocationService, LocationService>()
.AddSingleton(_ => BootStatus.Instantiate())
.AddScoped<IClock>(_ => new ZonedClock(SystemClock.Instance, DateTimeZone.Utc, CalendarSystem.Iso))
.AddHostedService<BootService>()
.AddMvcCore()
.AddJsonFormatters()
.AddApiExplorer()
.AddAuthorization();
/* Other code, not relevant here. */
}
在我的 HTTP 控制器中,我有一个 GET:
[HttpGet(nameof(Location))]
public async Task<IActionResult> Location(
LocationQueryParameters queryParams)
{
if (!ModelState.IsValid)
{
return new BadRequestObjectResult(ModelState);
}
var response = await locationService.Retrieve(
queryParams.Category,
queryParams.ItemsCount);
return StatusCode(200, response);
}
这是我的参数对象:
public class LocationQueryParameters
{
[FromQuery(Name = "category")]
[BindRequired]
public string Category { get; set; }
[FromQuery(Name = "itemsCount")]
[BindRequired]
[Range(1, 999)]
public int ItemsCount { get; set; }
}
Range 属性被完全忽略。同样,如果我将 StringLength 属性附加到字符串属性,它会被忽略。我还尝试编写自定义 ValidationAttribute,但单步执行代码从未遇到 IsValid 方法。BindRequired 和 FromQuery 工作正常,那么我做错了什么会阻止数据注释样式的验证?我不想手动编写所有验证。
解决方案
这里的问题是.AddMvcCore()
,这是.AddMvc()
. 在此处查看更多信息:https ://offering.solutions/blog/articles/2017/02/07/difference-between-addmvc-addmvcore/
解决方案是添加.AddDataAnnotations()
一个通常由以下人员添加的服务.AddMvc()
:
public void ConfigureServices(IServiceCollection services)
{
services
.AddSingleton<ILocationService, LocationService>()
.AddSingleton(_ => BootStatus.Instantiate())
.AddScoped<IClock>(_ => new ZonedClock(SystemClock.Instance, DateTimeZone.Utc, CalendarSystem.Iso))
.AddHostedService<BootService>()
.AddMvcCore()
.AddDataAnnotations()
.AddJsonFormatters()
.AddApiExplorer()
.AddAuthorization();
/* Other code, not relevant here. */
}
推荐阅读
- javascript - 如何将文件中的多个 JavaScript 对象存储到变量中
- node.js - npm 中的身份验证令牌是什么?
- ios - Swift - AudioKit AKMidi 到 AKSequencer
- powershell - 安装模块 PowerShellGet 时发出警告
- android - EPSON 的问题,找不到“libepos2.so”
- python - 如何从我的 numpy 数组中获取列名?
- android - 如何解决方法 getDownloadUrl()
- c# - 通过 c# 从 Oracle long raw 读取 tiff 图像不起作用
- c# - 是否可以创建创建类实例的循环?
- macos - 项目转移到 Macbook 时出现会话错误