Optional parameters in ASP.NET Web API

[Originally Posted By]: http://stackoverflow.com/questions/11862069/optional-parameters-in-asp-net-web-api

I need to implement the following WebAPI method:


All of the parameters can be null, i.e. the caller can specify from 0 to all 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 less than 5 parameters, it replies with a 404saying

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?


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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s