2008-10-20 64 views
36

如何在ASP.NET MVC框架中生成友好的URL?例如,我们已经得到了类似如下的URL:如何在ASP.NET MVC中创建友好的URL?

http://site/catalogue/BrowseByStyleLevel/1

的1是研究水平(高等教育在这种情况下),以浏览的ID,但I'l要重新格式化的URL在同一方式StackOverflow做到了。

例如,这两个网址会带你到同一个地方:

https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages

https://stackoverflow.com/questions/119323/

编辑: URL的友好的部分被称为a slug

+0

什么样的URL的你到底想看到的,这一个 /目录/ BrowseByStyleLevel/1 /高? 或/ catalog/BrowseByStyleLevel/Higher? – liggett78 2008-10-20 10:35:12

+0

理想情况下,第二个,但我需要Id保存每次基于文本查找。 – Kieron 2008-10-20 14:01:26

+0

关于“ASP.NET MVC 5”解决方案,请参阅http://stackoverflow.com/a/20662188/1298685。 – 2013-12-24 09:37:01

回答

47

有两个步骤来解决这个问题。首先,创建一个新的路由或更改默认的路由,接受额外的参数:

routes.MapRoute( "Default", // Route name 
        "{controller}/{action}/{id}/{ignoreThisBit}", 
        new { controller = "Home", 
         action = "Index", 
         id = "", 
         ignoreThisBit = ""} // Parameter defaults) 

现在你可以在你的URI的末尾键入任何你想和应用程序将忽略它。

渲染时的链接,你需要添加的“友好”的文本:

<%= Html.ActionLink("Link text", "ActionName", "ControllerName", 
        new { id = 1234, ignoreThisBit="friendly-text-here" }); 
1

你有在Global.asax

routes.MapRoute(
        "Default", // Route name 
        "{controller}/{action}/{id}", // URL with parameters 
        new { controller = "Home", action = "Index", id = ""} 
        // Parameter defaults) 

的路线,你可以定义自己的路线,如:

控制器是控制器文件夹中的CS类。

您可以使用您选择的名称来定义您的ID。

系统会将值传递给您的actionResult方法。

您可以在此处详细了解此步骤:http://www.asp.net/learn/mvc/tutorial-05-cs.aspx

1

这是怎么了我已经实现了我的申请蛞蝓URL。 注意:默认的Maproute不应该改变,路由也会按照添加到路由列表的顺序进行处理。

routes.MapRoute(
    "Default", // Route name 
    "{controller}/{action}/{id}", // URL with parameters 
    new { controller = "Home", 
      action = "Index", 
      id = UrlParameter.Optional 
    } // Parameter defaults 
); 
routes.MapRoute("Place", "{controller}/{action}/{id}/{slug}", new { controller = "Place", action = "Details", id = UrlParameter.Optional,slug="" });