[英]System.ComponentModel.DataAnnotations attribute not recognized. Unable to use StringLength attibute to verify empty string
I am looking for a way to validate data contracts in ASP.net web API.我正在寻找一种方法来验证 ASP.net web API 中的数据合同。 When a client hits POST request, I want to validate the request body before doing any processing.
当客户端点击 POST 请求时,我想在进行任何处理之前验证请求正文。 Request:
要求:
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
}'
Data contract:数据合约:
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: Controller:
namespace Person.Controllers
{
public sealed class PersonController : Controller, IPersonController
{
[HttpPost]
[ValidatModel]
[Route("Person")]
public Task<Person> RegisterOrUpdateDataset([FromBody] Person person)
{
// Method body
}
}
}
ValidateModel Attribute:验证模型属性:
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
}
}
}
}
I want to verify that the request body should not contain empty person name.我想验证请求正文不应包含空的人名。 For that, I tried using System.ComponentModel.DataAnnotations StringLength attribute but somehow this attribute is not honoured.
为此,我尝试使用 System.ComponentModel.DataAnnotations StringLength 属性,但不知何故,这个属性没有得到尊重。 I have also tried using MinLength(1) attribute but still facing the same issue.
我也尝试过使用 MinLength(1) 属性,但仍然面临同样的问题。
Add [Required] to your model.将 [必需] 添加到您的 model。 It should work!
它应该工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.