关于发布的动作参数的ModelValidation没有发生 [英] ModelValidation on posted action parameter not happening

查看:71
本文介绍了关于发布的动作参数的ModelValidation没有发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆