Chr*_*s S 7 asp.net-mvc asp.net-mvc-routing asp.net-mvc-3
我有一个网址
我想变成
这也可能是http://www.roadkillwiki.org/Page/my-url-with-spaces - 参数是一个字符串.我尝试过的路线设置是:
routes.MapRoute(
"ControllerDefault",
"{controller}/{id}",
new { controller = "Page", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
然而,这干扰了MVC项目带来的默认"id"路由.有没有办法实现这个目标?
Dan*_*zzi 17
您不需要丢失默认路由.避免路线相互干扰的关键是对它们进行排序,以便更具体的规则先于不太具体的规则.例如:
// Your specialized route
routes.MapRoute(
"Page",
"Page/{slug}",
new { controller = "Page", action = "Index" }
);
// Default MVC route (fallback)
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Run Code Online (Sandbox Code Playgroud)
然后你的PageController看起来像这样:
using System.Web.Mvc;
public class PageController : Controller
{
public string Index(string slug)
{
// find page by slug
}
}
Run Code Online (Sandbox Code Playgroud)
也就是说,我强烈建议你这样做:
// Your specialized route
routes.MapRoute(
"Page",
"Page/{id}/{slug}",
new { controller = "Page", action = "Index", slug = UrlParameter.Optional }
);
// MVC's default route (fallback)
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Run Code Online (Sandbox Code Playgroud)
而你的PageController:
using System.Web.Mvc;
public class PageController : Controller
{
public string Index(int id)
{
// find page by ID
}
}
Run Code Online (Sandbox Code Playgroud)
通过在URL的开头(如StackOverflow)或最后包含页面ID,您可以忽略slug,而是通过ID检索页面.如果您的用户更改页面名称,这将为您节省大量的麻烦.我经历过这个,很痛苦; 你基本上必须保留你的网页过去所有名字的记录,这样你的访问者/搜索引擎每次重命名页面都不会得到404.
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
21603 次 |
| 最近记录: |