allow hyphens in URLs for asp.net mvc 2 controller names
Asked Answered
D

5

6
[ActionName("about-us")]
public ActionResult EditDetails(int id)
{
    // your code
}

The above works for actions but I would like to be able to do the same (or similar) for controllers, ie have a hyphen in the URL name too. Is there any easy way to achieve this (I tried the ActionName attribute but no luck)

Dykes answered 12/3, 2011 at 8:19 Comment(0)
A
8

Easiest way would be adding a custom route:

routes.MapRoute("RouteName", "controler-name/{action}/{id}", new { controller = "ControllerName", action = "Index", id = "" });

I haven't seen a controller name attribute like that before although it may be possible.

Antigua answered 12/3, 2011 at 8:32 Comment(0)
H
3

You can use custom route handler to give you needed functionality:

public class HyphenatedRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
        requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");

        return base.GetHttpHandler(requestContext);
    }
}

And the route should be registered using that handler:

var route = routes.MapRoute(
    "Some Action",
    "{controller}/{action}/{id}"
);

route.RouteHandler = new HyphenatedRouteHandler();

There is a similar quastion asked here: ASP.net MVC support for URL's with hyphens

Hirsch answered 16/6, 2011 at 14:31 Comment(0)
D
1

Hyphenated route in the route table should be before the default route.

routes.MapRoute(
                  "InformationAbout", 
                  "information-about/{action}/{id}", 
                   new { controller = "InformationAbout", action = "Index", id = "" }
                );

 routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
Decomposition answered 2/2, 2012 at 21:21 Comment(0)
T
0

Maybe this works:

public class CustomControllerFactory : DefaultControllerFactory {

   protected override Type GetControllerType(RequestContext requestContext, string controllerName) {
      return base.GetControllerType(requestContext, controllerName.Replace("-", ""));
   }
}
Tetrabasic answered 14/3, 2011 at 3:12 Comment(0)
P
0

May be here is the correct answer to the question. All other are workarounds which work for a single url but this one is a generic approach

http://blog.didsburydesign.com/2010/02/how-to-allow-hyphens-in-urls-using-asp-net-mvc-2/

Proudfoot answered 17/11, 2012 at 20:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.