0

I've got a get method which accepts a set of optional parameters.

    public HttpResponseMessage Get([FromUri] Parameter parameter)
    ---------------------------
    public class Parameter
    {
       public string TransactionStatus { get; set; }
       public string AllVersions { get; set; }
       public string RunNumber { get; set; }
    }

I'm calling api using api/item?transactionStatus=1 or api/item?transactionStatus=1&allVersions=true. My question is how could I catch/prevent the misspelled parameters in request? Let's say if api/item?transactionStatus=1&MISSPELLED=true is called, I want to throw an error "url is not valid".

Andrei
  • 119
  • 1
  • 1
  • 10
  • See http://stackoverflow.com/a/22423612/1260204. You would have to iterate over the query string parameters and included parameter that is not defined in your expected set of parameters would have to cause the code to throw an exception. I would recommend against it. If the parameter is optional and not included even due to bad spelling then treat it as if it were not there. Only return errors when a non-optional parameter is not included or configure the route in such a way that the framework handles it (default). – Igor Oct 14 '16 at 11:28
  • Just a note, if this is a public API, I have seen libraries that do things like append `&ts=TIMESTAMP` and such to ensure no caching occurs. You may want to be careful that you don't break such things. – dmeglio Oct 14 '16 at 13:04
  • That helps. Thank you. When parameter is misspelled I still want to throw an error even if it's optional. As if parameter is ignored due to bad spelling behind the scenes the user will not notice that and treat the output as legit. – Andrei Oct 14 '16 at 13:04

1 Answers1

2

Here's a way using LINQ:

  1. Fetch the query parameters as NameValuePairs, selecting just the keys and convert to a List.

  2. Get the properties for the Parameter class, selecting just the name and convert to a List.

  3. Find the set difference of both Lists.

Here's some code:

var queryParameters = Request.GetQueryNameValuePairs().Select(q => q.Key).ToList();
var parameterProperties = typeof(Parameter).GetProperties().Select(p => p.Name).ToList();
var difference = queryParameters.Except(parameterProperties);

The difference will be an IEnumerable containing the parameters passed in the URL that are NOT properties in your Parameter class. So if this is not empty you can throw an error and even tell them which parameters were not expected/misspelled.

Ben Hall
  • 1,353
  • 10
  • 19