首页 > 解决方案 > System.ComponentModel.DataAnnotations 属性无法识别。无法使用 StringLength 属性验证空字符串

问题描述

我正在寻找一种在 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;}
    }
}

控制器:

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) 属性,但仍然面临同样的问题。

标签: c#asp.net-web-api

解决方案


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


推荐阅读