ModelValidation on posted action parameter not happening

与世无争的帅哥 提交于 2019-12-12 04:02:57

问题


Why doesn't ASP.NET Core validate [FromBody] attributed action parameters? In the example below the paramter value of type SomeClass does not get validated. It doesn't even appear in the ModelState dictionary (only id). this.ModelState.IsValid is always true, even though the Name property is set to a string longer than 2 letters.

Even TryValidateModel is always true no matter what the request body contains (JSON).

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();
    }
}

and

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:


You need to register MVC data annotation. It is not added by default when you use the light AddMvcCore method instead of AddMvc. Modify your ConfigureServices method:

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


来源:https://stackoverflow.com/questions/44979691/modelvalidation-on-posted-action-parameter-not-happening

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!