1

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

Let say my vallidation is like ,

  • Every action method must have 2 non empty paramaters named - A and B.

  • A must be greater than B and both should exists in DB.

  • So on.

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");
            }

        }
user1926138
  • 1,464
  • 7
  • 34
  • 53
  • for this kind of thing you can use an Action Filter Attribute. https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api#handling-validation-errorsi gives a basic example of the concept – ADyson Jun 27 '18 at 08:10

0 Answers0