0

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; }
    }
}
Set
  • 47,577
  • 22
  • 132
  • 150
MarcusK
  • 194
  • 1
  • 11

1 Answers1

2

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
Set
  • 47,577
  • 22
  • 132
  • 150