user1926138
user1926138

Reputation: 1514

How to call a specific function before Action Method execution in web API?

I have a requirement to validate 2 paramaters before all Action method execution in WEB API2.

Let say my vallidation is like ,

Let say I have an action method TestValues. I need to check above condition in Action method and return a status code if validation fails else need to execute other code.

How to do it for all action method from a sinlge place ? Is there a common method that get executed always?

My code is like

 [HttpPost]
        public HttpResponseMessage TestValues(string a, string b, ....)
        {

            if(string.IsNullOrWhiteSpace(a) || string.IsNullOrWhiteSpace(b))
            {
            return Request.CreateResponse(HttpStatusCode.Unauthorized, "Paramater is empty.");
            }
            else if(CompareValue(a, b) //CompareValue is a user defined method
            {
            return Request.CreateResponse(HttpStatusCode.Unauthorized, "Comparision failed");
            }
            else{
                //Execute code
                 return Request.CreateResponse(HttpStatusCode.OK, "Success");
            }

        }

Upvotes: 1

Views: 1126

Answers (0)

Related Questions