Attribute Routing for Multiple DateTime Parameters

I defined an attribute route that takes two parameters as datetime

  [Route("{controller}/{action}/{*startDate:datetime}/{*endDate:datetime}")]
        public bool OverView(DateTime startDate,DateTime endDate)
        {
            var dt = startDate.ToString("yyyy-MM-dd");
            return true;
        }

But not sure how this is possible. An attribute route works fine for a single parameter, but is not sure how it will work for 2 parameters. It is also difficult to understand how it will distinguish two parmeters from url

A single parameter that works great

http://domain.com/Home/overview/2014/02/01

What will be the URL for the two parameters? I tried the following but got an exception.

http://domain.com/Home/overview/2014/02/01/2014/02/04

Exception
A catch-all parameter can only appear as the last segment of the route URL.
Parameter name: routeUrl
+4
source share
1 answer

First opportunity

, /, URL... MVC , , , .

,

/home/overview/2014/02/01

/home/overview/2014-02-01

, datetime. :

[Route("{controller}/{action}/{startDate:datetime?}/{endDate:datetime?}")]
public ActionResult OverView(DateTime? startDate, DateTime? endDate)
{
    ...
}

, (/ - -), , - (.. )

. 0, 3, 6 . .

[Route("{controller}/{action}/{*dateRange}")]
public ActionResult Overview(string dateRange)
{
    int numberOfSegments = dateRange.Split('/').Length;

    if (dateRange.EndsWith("/"))
    {
        numberOfSegments--;
    }

    switch (numberOfSegments)
    {
        case 0:
            // no dates provided
            ...
            break;
        case 3:
            // only one date provided
            ...
            break;
        case 6:
            // two dates privided
            ...
            break;
        default:
            // invalid number of route segments
            ...
            break;
    }
}
+5

Source: https://habr.com/ru/post/1525469/


All Articles