how can i validate model in asp.net 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.

Web-Api-Validation

as asked on facebook group


Asked by:- vikas_jk
0
: 3110 At:- 6/22/2017 1:33:21 PM
asp.net web-api validation







1 Answers
profileImage Answered by:- vikas_jk

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

web-api-validation-postman.png

that's it, hope it will resolve your issue

 

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






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

Full Name *

Email *




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