Asp.Net MVC: How do I enable dashes in my urls?

前端 未结 9 1047
礼貌的吻别
礼貌的吻别 2020-11-28 21:52

I\'d like to have dashes separate words in my URLs. So instead of:

/MyController/MyAction

I\'d like:

/My-Controller/My-Act         


        
9条回答
  •  爱一瞬间的悲伤
    2020-11-28 22:53

    You could create a custom route handler as shown in this blog:

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

    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 new route:

    routes.Add(
                new Route("{controller}/{action}/{id}", 
                    new RouteValueDictionary(
                        new { controller = "Default", action = "Index", id = "" }),
                        new HyphenatedRouteHandler())
            );
    

    A very similar question was asked here: ASP.net MVC support for URL's with hyphens

提交回复
热议问题