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

2020-01-26 03:14发布

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

/MyController/MyAction

I'd like:

/My-Controller/My-Action

Is this possible?

标签: asp.net-mvc
9条回答
女痞
2楼-- · 2020-01-26 04:12

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.

查看更多
▲ chillily
3楼-- · 2020-01-26 04:15

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

查看更多
叛逆
4楼-- · 2020-01-26 04:17

Asp.Net MVC 5 will support attribute routing, allowing more explicit control over route names. Sample usage will look like:

[RoutePrefix("dogs-and-cats")]
public class DogsAndCatsController : Controller
{
    [HttpGet("living-together")]
    public ViewResult LivingTogether() { ... }

    [HttpPost("mass-hysteria")]
    public ViewResult MassHysteria() { }
}

To get this behavior for projects using Asp.Net MVC prior to v5, similar functionality can be found with the AttributeRouting project (also available as a nuget). In fact, Microsoft reached out to the author of AttributeRouting to help them with their implementation for MVC 5.

查看更多
登录 后发表回答