39

如何在 ASP.NET MVC 框架中生成友好的 URL?例如,我们有一个如下所示的 URL:

http://site/catalogue/BrowseByStyleLevel/1

1 是要浏览的学习级别(在本例中为更高)的 ID,但我想以与 StackOverflow 相同的方式重新格式化 URL。

例如,这两个 URL 会将您带到同一个地方:

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

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

编辑: url 的友好部分称为slug

4

3 回答 3

52

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 )

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" });
于 2008-10-20T13:15:29.807 回答
3

This is how I have implemented the slug URL on my application. Note: The default Maproute should not be changed and also the routes are processed in the order in which they're added to the route list.

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="" });
于 2011-07-28T21:38:29.467 回答
1

你在 global.asax 上有一条路线

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

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

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

您可以定义您的 id - 使用您选择的名称。

the system will pass the value to your actionResult method.

you can read more about this step here : http://www.asp.net/learn/mvc/tutorial-05-cs.aspx

于 2008-10-20T10:20:53.593 回答