dferraro dferraro - 19 days ago 6
C# Question

Optional DateTime Web API

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?

Answer

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>();
        }
}