发布的动作参数的ModelValidation未发生

时间:2017-07-07 21:11:03

标签: asp.net-core asp.net-core-mvc model-validation

为什么ASP.NET Core不验证[FromBody]归因的操作参数?在下面的示例中,类型为value的参数SomeClass未经过验证。它甚至不会出现在ModelState字典中(仅id)。 this.ModelState.IsValid始终为true,即使Name属性设置为长度超过2个字母的字符串。

无论请求正文包含什么(JSON),偶数TryValidateModel始终为true

Sample Repo here

public class Startup
{
    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddMvcCore()
            .AddJsonFormatters();
    }

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();

        app.UseMvc();
    }
}

using Microsoft.AspNetCore.Mvc;
using System;
using System.ComponentModel.DataAnnotations;

namespace WebApplication3.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [HttpPut("{id:int}")]
        public IActionResult Put(
            int id,
            [FromBody]SomeClass value)
        {
            if (this.ModelState.IsValid == false)
                throw new Exception();

            if (this.TryValidateModel(value) == false)
                throw new Exception();

            return this.BadRequest(this.ModelState);
        }
    }

    public class SomeClass
    {
        [StringLength(2)]
        [Required(AllowEmptyStrings = false)]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        public string Name { get; set; }
    }
}

1 个答案:

答案 0 :(得分:2)

您需要注册MVC数据注释。使用简单AddMvcCore方法而不是AddMvc时,默认情况下不会添加。修改您的ConfigureServices方法:

services
   .AddMvcCore()
   .AddJsonFormatters()
   .AddDataAnnotations(); // add this line