Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ASP.NET MVC have any DateTime route constraints?

does ASP.NET MVC contain any route contraints baked into the code? if so, how do i define a date-time constraint?

eg. url:

http://mydomain.com/{versionDate}/{controller}/{action}
http://mydomain.com/2010-01-20/search/posts

cheers :)

like image 434
Pure.Krome Avatar asked Mar 02 '10 03:03

Pure.Krome


2 Answers

I ended up making my own route constraint. only took a few mins.

using System;
using System.Web;
using System.Web.Routing;

namespace Whatever.Your.Funky.Cold.Medina.Namespace.Is
{
    public class DateTimeRouteConstraint : IRouteConstraint
    {
        #region IRouteConstraint Members

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
                          RouteDirection routeDirection)
        {
            DateTime dateTime;

            return DateTime.TryParse(values[parameterName] as string, out dateTime);
        }

        #endregion
    }
}

simple :P

like image 70
Pure.Krome Avatar answered Sep 29 '22 16:09

Pure.Krome


You could also set up a constraint on the route, something like so. The regular expression used is not very robust, so you should refine it.

routes.MapRoute( 
    "Version", "
    {versionDate}/{controller}/{action}", 
    new {controller="Search", action="Posts"}, 
    new {versionDate= @"\d\d\d\d-\d\d-\d\d" } 
    ); 

Information from here.

like image 26
37Stars Avatar answered Sep 29 '22 18:09

37Stars