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

前端 未结 9 1005
礼貌的吻别
礼貌的吻别 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

    0 讨论(0)
  • 2020-11-28 22:56

    You could write a custom route that derives from the Route class GetRouteData to strip dashes, but when you call the APIs to generate a URL, you'll have to remember to include the dashes for action name and controller name.

    That shouldn't be too hard.

    0 讨论(0)
  • 2020-11-28 22:56

    If you have access to the IIS URL Rewrite module ( http://blogs.iis.net/ruslany/archive/2009/04/08/10-url-rewriting-tips-and-tricks.aspx ), you can simply rewrite the URLs.

    Requests to /my-controller/my-action can be rewritten to /mycontroller/myaction and then there is no need to write custom handlers or anything else. Visitors get pretty urls and you get ones MVC can understand.

    Here's an example for one controller and action, but you could modify this to be a more generic solution:

    <rewrite>
      <rules>
        <rule name="Dashes, damnit">
          <match url="^my-controller(.*)" />
          <action type="Rewrite" url="MyController/Index{R:1}" />
        </rule>
      </rules>
    </rewrite>
    

    The possible downside to this is you'll have to switch your project to use IIS Express or IIS for rewrites to work during development.

    0 讨论(0)
提交回复
热议问题