I am looking for a way to validate data contracts in ASP.net web API. When a client hits POST request, I want to validate the request body before doing any processing. 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:
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. I have also tried using MinLength(1) attribute but still facing the same issue.
Add [Required] to your model. It should work!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.