【问题标题】:ASP Net Core model validation Range attribute is ignoredASP Net Core 模型验证 Range 属性被忽略
【发布时间】:2019-01-10 17:18:05
【问题描述】:

我正在使用 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 工作正常,那么我做错了什么会阻止验证的数据注释样式?我不想手动编写所有验证。

【问题讨论】:

  • 是否有任何演示可以重现您的问题?我用你的代码和Microsoft.AspNetCore.Mvc 2.1.3做了一个测试,当https://localhost:44315/location?category=123&amp;itemscount=11111返回预期值{"itemsCount":["The field ItemsCount must be between 1 and 999."]}
  • @TaoZhou 我没有可用的演示,这是一个更大项目的一部分。我会看看我是否可以在一个不太复杂的例子中重现它并更新这篇文章。

标签: c# validation asp.net-core attributes range


【解决方案1】:

这里的问题是.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. */
}

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 2011-02-09
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多