Reputation: 73
I'm looking for a proper way to handle empty parameters in a query string. Web Api does not accept query strings as "?id=1&category=", which seems reasonable, but I need to handle this case.
The quick and dirty solution is to use a custom value which will be interpreted on the server side (say "(empty)" for example) but I'm not satisfied with it...
Any suggestion ?
Thanks.
Upvotes: 3
Views: 5637
Reputation: 231
You can use this attribute to achieve what you want.
[DisplayFormat(ConvertEmptyStringToNull = false)]
If "category" is missing then it will be null. Otherwise, if "category=" or "category= " then will be an empty string or whitespace.
Upvotes: 1
Reputation: 2201
One way I have dealt with this in the past is to make a class to hold your paramaters and then use to ModelBinder attribute to bind your query parameters to the class properties.
So your class would look something like this:
public class QueryParams
{
public string Category {get; set;}
public int Id {get; set;}
}
And the method in your api controller would look like this:
public objectToReturn Get([ModelBinder] QueryParams)
{
//code here
}
This way if one of the parameters in the query string has no value it will simply be ignored.
Upvotes: 3