问题
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