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

http://site/catalogue/BrowseByStyleLevel/1

1是研究级别的Id(在这种情况下更高)要浏览,但我想以与StackOverflow相同的方式重新格式化URL。

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

  

https://stackoverflow.com/questions/119323/nested-for-loops -in-不同语言

     

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

编辑:网址的友好部分称为 slug

有帮助吗?

解决方案

解决此问题有两个步骤。首先,创建一个新路由或更改默认路由以接受其他参数:

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" });

其他提示

这就是我在应用程序上实现slug 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="" });

你在global.asax上有一条路线

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

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

controller是controllers文件夹中的cs类。

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

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top