2

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.