开发者

Does ASP.NET MVC have any DateTime route constraints?

does AS开发者_如何学编程P.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 :)


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


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.


all of the framework is overide-able so it's possible, with a great deal of pain, to overide the default behaviour of the route engine but i agree with @jrista in that you might want to make it a parameter of the controller else mvc will expect to find /search/posts within the 2010-01-20 folder

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜