Hi, anyone know how to make Input Validation in Web API? Data annotations do not work; I want to make it like in MVC [Required] or [RegularExpression] attributes. Any ideas?
I made something like this, but it's not working.
as asked on facebook group
Hello
I have created this model and it worked for me, let me show you code and class
public class Person
{
[DataMember]
[Required(ErrorMessage ="User name is requried")]
public string Name { get; set; }
[DataMember]
[Required(ErrorMessage = "First name is requried")]
public string FirstName { get; set; }
}
and this was the code in web-api controller
[HttpPost]
public HttpResponseMessage SaveTest(Person p)
{
if(ModelState.IsValid)
{
//save it in db
return Request.CreateResponse(HttpStatusCode.OK);
}
else{
var errors = new List<string>();
foreach (var state in ModelState)
{
foreach (var error in state.Value.Errors)
{
errors.Add(error.ErrorMessage);
}
}
return Request.CreateResponse(HttpStatusCode.Forbidden, errors);
}
}
And I was able to get error in postman when first name was empty
that's it, hope it will resolve your issue
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly