繁体   English   中英

System.ComponentModel.DataAnnotations 属性无法识别。 无法使用 StringLength 属性验证空字符串

[英]System.ComponentModel.DataAnnotations attribute not recognized. Unable to use StringLength attibute to verify empty string

我正在寻找一种方法来验证 ASP.net web API 中的数据合同。 当客户端点击 POST 请求时,我想在进行任何处理之前验证请求正文。 要求:

curl --location --request POST 'http://some-url/PersonService/Person' \
--header 'Content-Type: application/json' \
--header 'Content-Type: text/plain' \
--data-raw '{
  "Name": "John",
  "Age": 23
}'

数据合约:

namspace Person.DataContracts {
    [DataContract]
    class Person{

        [DataMember(IsRequired = true)]
        [StringLength(30, MinimumLength = 1)]
        private string Name {get; set;}

        [DataMember]
        private int Age {get; set;}
    }
}

Controller:

namespace Person.Controllers
{
    public sealed class PersonController : Controller, IPersonController
    {
        [HttpPost]
        [ValidatModel]
        [Route("Person")]
        public Task<Person> RegisterOrUpdateDataset([FromBody] Person person)
        {
            // Method body
        }
     }
}

验证模型属性:

namespace Person.Filters
{
    using System;
    using Microsoft.AspNetCore.Mvc.Filters;

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                // handle validation failure
            }
        }
    }
}

我想验证请求正文不应包含空的人名。 为此,我尝试使用 System.ComponentModel.DataAnnotations StringLength 属性,但不知何故,这个属性没有得到尊重。 我也尝试过使用 MinLength(1) 属性,但仍然面临同样的问题。

将 [必需] 添加到您的 model。 它应该工作!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM