Route value with dash

I have this route:

routes.MapRoute( "News", "News/{id}-{alias}", new { controller = "News", action = "Show" }, new { id = @"^[0-9]+$" }, namespaces: new[] { "Site.Controllers" } ); 

This route works for the url:

 http://localhost:54010/News/6-news 

But not working for the url:

 http://localhost:54010/News/6-nice-news 

How to use dashes in my alias route value?

EDITED

Follow these steps:

 "News/{id}_{alias}" 

works for both urls:

 http://localhost:54010/News/6_news http://localhost:54010/News/6_nice-news 
+4
source share
1 answer

The problem is your template: News/{id}-{alias} , because Routeting processes the templates eagerly.

Thus, the url http://localhost:54010/News/6-news generates the following tokens:

 id = 6, alias = news 

But http://localhost:54010/News/6-nice-news generates the following tokens:

 id = 6-nice, alias = news 

And the id = 6-nice token will not be able to fulfill your routing ban @"^[0-9]+$". so you get 404.

Now you can configure this MVC behavior so that you have the following options:

  • Use something else than a dash. As you noticed, dashes and hyphens are combined.
  • Take the flem approach and parse inside the id and alias inside your controller action.
  • You can create a custom Route that will be used for re-parsing. For example, converting id = 6-nice, alias = news to id = 6, alias = news-nice

I will show you the raw (without error handling or the right coding methods!) Implementation of option 3 to get you started.

So you need to inherit from Route :

 public class MyRoute : Route { public MyRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens) : base(url, defaults, constraints, dataTokens, new MvcRouteHandler()) { } protected override bool ProcessConstraint(HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { var parts = ((string) values["id"]).Split('-'); if (parts.Length > 1) { values["id"] = parts[0]; values["alias"] = // build up the alias part string.Join("-", parts.Skip(1)) + "-" + values["alias"]; } var processConstraint = base.ProcessConstraint(httpContext, constraint, parameterName, values, routeDirection); return processConstraint; } } 

Then you just need to register your route:

 routes.Add("News", new MyRoute("News/{id}-{alias}", new RouteValueDictionary(new {controller = "News", action = "Show"}), new RouteValueDictionary(new { id = @"^[0-9]+$" }), new RouteValueDictionary())); 
+3
source

All Articles