Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Api: Pass an empty parameter in a query string

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.

like image 262
jpo Avatar asked Jan 31 '26 17:01

jpo


1 Answers

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.

like image 144
James Avatar answered Feb 02 '26 23:02

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!