2017-07-07 25 views
0

爲什麼ASP.NET Core無法驗證[FromBody]屬性操作參數?在下面的示例中,類型SomeClass的參數value未得到驗證。它甚至不出現在ModelState字典中(僅限於id)。 this.ModelState.IsValid始終爲true,即使Name屬性設置爲長於2個字母的字符串也是如此。ModelValidation對發佈的操作參數沒有發生

即使TryValidateModel始終是true無論請求正文包含什麼(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(); 
    } 
} 

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

您需要註冊MVC數據註解。當您使用光AddMvcCore方法而不是AddMvc時,它不會默認添加。修改您的ConfigureServices方法:

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

Aaahhhh yes,非常感謝! – MarcusK