如何在 ASP.NET MVC 中创建友好的 URL?
如何在 ASP.NET MVC 框架中生成友好的 URL?例如,我们有一个如下所示的 URL:
How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this:
http://site/catalogue/BrowseByStyleLevel/1
1 是要浏览的研究级别的 ID(在这种情况下为更高),但我想以与 StackOverflow 相同的方式重新格式化 URL.
The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it.
例如,这两个 URL 会将您带到同一个地方:
For example, these two URLs will take you to the same place:
https://stackoverflow.com/questions/119323/nested-for-loops-不同语言
https://stackoverflow.com/questions/119323/
url 的友好部分被称为 slug.
The friendly part of the url is referred to as a slug.
解决这个问题有两个步骤.首先,创建一个新路由或更改默认路由以接受附加参数:
There are two steps to solve this problem. First, create a new route or change the default route to accept an additional parameter:
routes.MapRoute( "Default", // Route name
"{controller}/{action}/{id}/{ignoreThisBit}",
new { controller = "Home",
action = "Index",
id = "",
ignoreThisBit = ""} // Parameter defaults )
现在您可以在 URI 的末尾输入您想要的任何内容,应用程序将忽略它.
Now you can type whatever you want to at the end of your URI and the application will ignore it.
渲染链接时,需要添加友好"文本:
When you render the links, you need to add the "friendly" text:
<%= Html.ActionLink("Link text", "ActionName", "ControllerName",
new { id = 1234, ignoreThisBit="friendly-text-here" });