Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 704
dferraro Avatar asked Jan 27 '14 23:01

dferraro


2 Answers

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>();
        }
}
like image 147
sjkm Avatar answered Oct 06 '22 01:10

sjkm


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

like image 35
Horizon_Net Avatar answered Oct 05 '22 23:10

Horizon_Net