Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route Constraint Isnt working for ASP.NET MVC

Tags:

asp.net-mvc

Why would the route http://localhost:2222/2012-adidas-spring-classic/37, not get picked up from the below route match? I get a 404 error.

      public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*vti_inf}", new { vti_inf = @"(.*/)?_vti_inf.html(/.*)?" });
            routes.IgnoreRoute("{*vti_rpc}", new { vti_rpc = @"(.*/)?_vti_rpc(/.*)?" });

            #region API

            routes.MapRouteLowercase(
             "NamedHomeEvent",
             "{year}-{name}/{Id}",
             new { controller = "Event", action = "Index", year = DateTime.Now.Year },
             new { year = @"\d{4}", Id = @"\d+" }
            );



   public virtual ActionResult Index(int? id, int? year, string name)
        {
like image 525
Mike Flynn Avatar asked Oct 06 '22 13:10

Mike Flynn


1 Answers

The routing engine cannot help you here. You could write a custom route to handle this case:

public class MyRoute : Route
{
    public MyRoute()
        : base(
            "{year-name}/{id}",
            new RouteValueDictionary(new { controller = "Event", action = "Index", id = UrlParameter.Optional }),
            new RouteValueDictionary(new { id = @"\d*" }),
            new MvcRouteHandler()
        )
    {
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var routeData = base.GetRouteData(httpContext);
        if (routeData == null)
        {
            return null;
        }

        var yearName = (string)routeData.Values["year-name"];
        if (string.IsNullOrWhiteSpace(yearName))
        {
            return null;
        }

        var parts = yearName.Split(new[] { '-' }, 2, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length < 2)
        {
            return null;
        }

        var year = parts.First();
        int yearValue;
        if (!int.TryParse(year, out yearValue))
        {
            return null;
        }

        var name = parts.Last();

        routeData.Values.Add("year", year);
        routeData.Values.Add("name", name);

        return routeData;
    }
}

and then register this route:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{*vti_inf}", new { vti_inf = @"(.*/)?_vti_inf.html(/.*)?" });
    routes.IgnoreRoute("{*vti_rpc}", new { vti_rpc = @"(.*/)?_vti_rpc(/.*)?" });

    routes.Add("NamedHomeEvent", new MyRoute());
}
like image 54
Darin Dimitrov Avatar answered Oct 10 '22 02:10

Darin Dimitrov