c# - 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) 属性,但仍然面临同样的问题。
解决方案
将 [必需] 添加到您的模型。它应该工作!
推荐阅读
- javascript - 在 React 中处理多个导入的有效方法
- php - 将类似的表单输入存储为数组
- dask - Dask:为可视化()选择什么函数变量最好
- c# - 为什么 OnCollisionEnter2D / OnTriggerEnter2D 不起作用?
- firefox - 在没有隐私通知选项卡的情况下在 Firefox 中启动业力测试并禁用扩展
- amazon-web-services - AWS Route 53:更改自动创建的 NS 记录
- ruby-on-rails - 尝试 Heroku 运行 rake db:使用 cors 迁移时突然出现“配置”错误?
- karate - 支持从场景大纲传递到 JSON 文件
- python - 如何使用 django 创建子类?
- javascript - jQuery修改特定表格单元格的值