web api handle misspelled fromuri parameters

2019-09-04 01:40发布

问题:

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".

回答1:

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.