ASP Net Core模型验证Range属性被忽略

时间:2019-01-10 17:18:06

标签: c# validation asp.net-core attributes 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属性附加到string属性,则将其忽略。我也尝试编写一个自定义的ValidationAttribute,但单步执行代码绝对不会碰到IsValid方法。 BindRequired和FromQuery可以正常工作,那么我在做错什么,阻止了数据注释样式的验证?我不希望手动编写所有验证。

1 个答案:

答案 0 :(得分:0)

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