Nathan Agersea
Nathan Agersea

Reputation: 536

ASP.Net Core MVC DateTime Parameters

I wanted to share how I worked through using DateTime parameters in my .NET Core MVC Controllers. I used this to create a date range filter capability in my solution.

Incorrect

[HttpGet, Route("dateRange/{start}/{end}")]
public IActionResult Get(DateTime start, DateTime end)
{
    //invalid values (e.g. /bogus/52) get converted to a valid DateTime value of 1/1/0001 00:00:00.001
    if (start != DateTime.MinValue && end != DateTime.MinValue)
    {            
        if (start < end)
        {
            return Json(_Repo.GetByDateRange(start, end));
        }
    }
    return BadRequest("Invalid Date Range");
}

Upvotes: 2

Views: 1696

Answers (1)

Nathan Agersea
Nathan Agersea

Reputation: 536

The better way:

[HttpGet, Route("dateRange/{start:datetime}/{end:datetime}")]
public IActionResult Get(DateTime start, DateTime end)
{            
    if (start < end)
    {
        return Json(_Repo.GetByDateRange(start, end));
    }
    return BadRequest("Invalid Date Range");
}

The key is the :datetime Constraint in the Route Annotation. This instructs .NET to enforce DateTime and to return a 404 Response automatically for invalid param values. This is much cleaner than inspecting the input and handling bad responses in code.

Upvotes: 5

Related Questions