关于发布的动作参数的ModelValidation没有发生 [英] ModelValidation on posted action parameter not happening
问题描述
为什么ASP.NET Core不验证[FromBody]
属性操作参数?在下面的示例中,未验证类型为SomeClass
的参数value
.它甚至没有出现在ModelState词典中(仅id
).即使Name属性设置为长度超过2个字母的字符串,this.ModelState.IsValid
始终为true
.
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.
即使TryValidateModel
始终是true
,无论请求正文包含什么(JSON).
Even TryValidateModel
is always true
no matter what the request body contains (JSON).
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; }
}
}
推荐答案
您需要注册MVC数据注释.当您使用light AddMvcCore
方法而不是AddMvc
时,默认情况下不会添加它.修改您的ConfigureServices
方法:
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
这篇关于关于发布的动作参数的ModelValidation没有发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!