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

[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)


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.


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


也许这工作:

public class CustomControllerFactory : DefaultControllerFactory {

   protected override Type GetControllerType(RequestContext requestContext, string controllerName) {
      return base.GetControllerType(requestContext, controllerName.Replace("-", ""));
   }
}
链接地址: http://www.djcxy.com/p/23360.html

上一篇: ActionName的用途

下一篇: 允许在连接asp.net mvc 2控制器名称的连字符中使用连字符