3

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this solution works. However, this implies that I interpret a null value for my category as an empty string in my controller. I wish "category=" would be interpreted as string empty, and the absence of this parameter in my query string as null.
A way to get around this would be to add a constructor to the QueryParams class and then use it to assign string.empty to the Category property.
This is the way I'm dealing with a similar situation in a resource planning app where I have a customized DateTime that can be a straight datetime or a set of keywords like "On Hold" or a blank.
1

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.

1 Comment

Excellent--this is exactly what I've been looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.