Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional query string parameters in ASP.NET Web API

I need to implement the following WebAPI method:

/api/books?author=XXX&title=XXX&isbn=XXX&somethingelse=XXX&date=XXX 

All of the query string parameters can be null. That is, the caller can specify from 0 to all of the 5 parameters.

In MVC4 beta I used to do the following:

public class BooksController : ApiController {     // GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01     public string GetFindBooks(string author, string title, string isbn, string somethingelse, DateTime? date)      {         // ...     } } 

MVC4 RC doesn't behave like this anymore. If I specify fewer than 5 parameters, it replies with a 404 saying:

No action was found on the controller 'Books' that matches the request.

What is the correct method signature to make it behave like it used to, without having to specify the optional parameter in the URL routing?

like image 473
frapontillo Avatar asked Aug 08 '12 09:08

frapontillo


People also ask

How do I pass optional parameters in Web API?

Optional Parameters in Web API Attribute Routing and Default Values: You can make a URI parameter as optional by adding a question mark (“?”) to the route parameter. If you make a route parameter as optional then you must specify a default value by using parameter = value for the method parameter.

Can query parameters be optional?

As query parameters are not a fixed part of a path, they can be optional and can have default values.

Which is optional element when you define route config in Web API?

Web API uses URI as “DomainName/api/ControllerName/Id” by default where Id is the optional parameter. If we want to change the routing globally, then we have to change routing code in register Method in WebApiConfig.


1 Answers

This issue has been fixed in the regular release of MVC4. Now you can do:

public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null)  {     // ... } 

and everything will work out of the box.

like image 184
frapontillo Avatar answered Sep 19 '22 02:09

frapontillo