I have a class like this:
public class FooController : ApiController
{
[System.Web.Http.Route("live/topperformers")]
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public List<string> GetTopPerformers()
{
return new List<string>();
}
}
When I access it by going to "http://foo.com/live/topperformers", it works great. So now I want to add an optional DateTime param to this method, so I modify the method to take a DAteTime param, and make it nullable.
public class FooController : ApiController
{
[System.Web.Http.Route("live/topperformers/{dateTime:DateTime}")]
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public List<string> GetTopPerformers(DateTime? dateTime)
{
return new List<string>();
}
}
When I try to access the URL without a parameter, the same as I access before - it gives a 404. Pasing in the date value like " like "http://foo.com/live/topperformers/2010-01-01" works fine. But without the date, it gives 404.
I thought Web API supported optional params in this fashion? I can simply overload and have both versions, but is this possible with just one method?
Set the optional parameter = null. Try this:
public class FooController : ApiController
{
[System.Web.Http.Route("live/topperformers/{dateTime:DateTime?}")]
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public List<string> GetTopPerformers(DateTime? dateTime = null)
{
return new List<string>();
}
}
You missed to make your route paramter optional. Change your code to the following
public class FooController : ApiController
{
[System.Web.Http.Route("live/topperformers/{dateTime:datetime?}")]
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public List<string> GetTopPerformers(DateTime? dateTime)
{
return new List<string>();
}
}
The question mark in the route is important. If you miss it it will be handled like a required paramter (that's why you get a 404). For more information have a look at Optional URI Parameters and Default Values
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With