how can i validate model in web api?

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

Asked by:- vikas_jk
: 2863 At:- 6/22/2017 1:33:21 PM web-api validation

1 Answers
profileImage Answered by:- vikas_jk


I have created this model and it worked for me, let me show you code and class

public class Person
        [Required(ErrorMessage ="User name is requried")]
        public string Name { get; set; }

        [Required(ErrorMessage = "First name is requried")]
        public string FirstName { get; set; }

and this was the code in web-api controller

        public HttpResponseMessage SaveTest(Person p)
                //save it in db
                return Request.CreateResponse(HttpStatusCode.OK);
                var errors = new List<string>();
                foreach (var state in ModelState)
                    foreach (var error in state.Value.Errors)
                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


At:- 6/22/2017 1:58:28 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use