我有一個項目,我希望能夠表示以下不同類型的URL路徑/路由。MVC Url路由併發症
{controller}/{section}
{controller}/{section}/{id}
{controller}/{section}/{organization}
{controller}/{section}/{id}/{key}
{controller}/{section}/{organization}/{id}
{controller}/{section}/{organization}/{id}/{key}
我指定的路由映射在Global.asax的類似如下:
routes.MapRoute(
"Section", // Route name
"{controller}/{section}", // URL with parameters
new {
controller = "Poll",
action = "Section",
id = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
"SectionMember", // Route name
"{controller}/{section}/{id}", // URL with parameters
new {
controller = "Poll",
action = "SectionMember",
id = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
"SectionOrganization", // Route name
"{controller}/{section}/{organization}", // URL with parameters
new {
controller = "Poll",
action = "SectionOrganization",
id = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
"SectionOrganizationMember", // Route name
"{controller}/{section}/{organization}/{id}", // URL with parameters
new {
controller = "Poll",
action = "SectionOrganizationMember",
id = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
"SectionMemberKey", // Route name
"{controller}/{section}/{id}/{key}", // URL with parameters
new {
controller = "Poll",
action = "SectionMemberKey",
id = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
"SectionOrganizationMemberKey", // Route name
"{controller}/{section}/{organization}/{id}/{key}", // URL with parameters
new {
controller = "Poll",
action = "SectionOrganizationMemberKey",
id = UrlParameter.Optional
} // Parameter defaults
);
我已經在我的控制器下面的代碼:
public class PollController : Controller {
public ActionResult Section(string section) {
return View();
}
public ActionResult SectionMember(string section, int id) {
return View();
}
public ActionResult SectionOrganization(string section, string organization) {
return View();
}
public ActionResult SectionOrganizationMember(string section, string organization, int id) {
return View();
}
public ActionResult SectionMemberKey(string section, int id, string key) {
return View();
}
public ActionResult SectionOrganizationMemberKey(string section, string organization, int id, string key) {
return View();
}
}
好像有與URL路由相關的複雜性,因爲當我試圖訪問不需要路由的路由時,它會一直查找{id}參數,反之亦然。
我的設置是否顯示出任何嚴重的重疊,還是我完全錯過了某些東西?
編輯
一些示例URL的,我會用將是以下幾點:
- http://mysite.com/Poll/section
- http://mysite.com/Poll/section/1234
- http://mysite.com/Poll/section/organization/
- http://mysite.com/Poll/section/1234/key
- http://mysite.com/Poll/section/organization/1234
- http://mysite.com/Poll/section/organization/1234/key
你能給你可以使用一個URL的例子嗎? – jzm
問題可能在於您創建路線的順序。路由引擎將使用第一條匹配路線。一般來說,你想把最具體的路線放在最上面,而更一般的路線放在最下面。您可能需要玩弄創建路線的順序,以按照您的意圖進行工作。 – HTX9
我已經添加了如上所示的示例URLS – TheJediCowboy