0
ASP.NET Coreが有効なアクションパラメータ[FromBody]
を検証しないのはなぜですか?下の例では、SomeClass
のパラメーターvalue
は検証されません。 ModelState辞書には表示されません(id
のみ)。 this.ModelState.IsValid
は、Nameプロパティが2文字より長い文字列に設定されていても、常にtrue
です。投稿されたアクションパラメータのModelValidationが発生しない
Even TryValidateModel
でも、リクエストボディに含まれる内容(JSON)に関係なく、true
になります。
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; }
}
}
はい、ありがとうございます。 – MarcusK