locked
Looking for Best Way to Validate Web API Get Request RRS feed

  • Question

  • User292070449 posted

    Hi All,

    I have got a requirement like:

    To validate a GET request inputs to my web API action method, this is coming as query string parameters.

    Eg :-

    GET api/v1/Customer/{customerId}/Contacts?contactTypeId={contactTypeId}&apiKey={apiKey}

    From the above GET request I could able to validate the CustomerId using the Route constraints .Since the remaining portion(contactTypeId,apiKey) is coming as query string parameter, I could able to apply the route constraints on it .

    Please recommend the best way to do it.

    Method in my consideration is by using Action Filter.

    Thanks in advance.

    Thursday, November 5, 2015 12:39 PM

Answers

  • User-782957977 posted

    You can do model validation in Web Api get method like this

    Sample Model

        public class Contacts
        {
            [Required]
            [StringLength(10, MinimumLength = 3)]
            public string contactTypeId { get; set; }
            [Required]
            [StringLength(10, MinimumLength = 3)]
            public string apiKey { get; set; } 
        }

    Sample Get method

        [HttpGet]
            public Customer GetCustomer(int? id,[FromUri]Contacts contact)
            {
                if (ModelState.IsValid)
                {
    
                }
            }

    Get Url - /Api/Customer/10/GetCustomer?contactTypeId=test1&apiKey=test2

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 10, 2015 11:37 PM

All replies

  • User1066278571 posted

    Here's some examples

    http://damienbod.com/category/validation/

    A good way is to use model validation, but of course you could also do this in an Action Filter

    Greetings Damien

    Thursday, November 5, 2015 5:15 PM
  • User292070449 posted

    But is that possible to have model validaion on querystring values ..

    Tuesday, November 10, 2015 5:05 PM
  • User-782957977 posted

    You can do model validation in Web Api get method like this

    Sample Model

        public class Contacts
        {
            [Required]
            [StringLength(10, MinimumLength = 3)]
            public string contactTypeId { get; set; }
            [Required]
            [StringLength(10, MinimumLength = 3)]
            public string apiKey { get; set; } 
        }

    Sample Get method

        [HttpGet]
            public Customer GetCustomer(int? id,[FromUri]Contacts contact)
            {
                if (ModelState.IsValid)
                {
    
                }
            }

    Get Url - /Api/Customer/10/GetCustomer?contactTypeId=test1&apiKey=test2

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 10, 2015 11:37 PM
  • User292070449 posted

    Thanks a lot .. this is what i am looking for .. Thank you !!!

    Wednesday, November 11, 2015 3:55 PM