我的MVC项目中的路由问题无法正常工作......
我希望 Views > Shared
文件夹中的所有视图都像这样:
Error.cshtml(默认)Index.cshtml(默认)Overview.cshtml(我自定义)Recordings.cshtml(我自定义)
然后我创建了一个共享控制器来处理所有这样的视图:
public class SharedController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Error()
{
return View();
}
public ActionResult Overview()
{
return View();
}
public ActionResult Recordings()
{
return View();
}
}
我的 RouteConfig.cs
看起来像这样:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Map to specific pages under Shared controller:
routes.MapRoute("SharedPages", "{action}/{id}",
new { controller = "Shared", action = @"Overview|Recordings", id = UrlParameter.Optional });
// Use the default rout for all other pages:
routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "Shared", action = "Index", id = UrlParameter.Optional }
);
// Show the Error page for anything else (404):
routes.MapRoute("Error", "{*url}",
new { controller = "Shared", action = "Error" }
);
}
我希望路由工作如下:
://(url)/(root - 未指定操作) - > Shared / Index.cshtml://(url)/ Index - > Shared / Index.cshtml://(url)/ Overview - > Shared / Overview.cshtml://(url)/ Recordings - > Shared / Recordings.cshtml://(url)/ whatever(或者如果发生错误) - > Shared / Error.cshtml
但它没有按预期工作 . 如果我去 ://(url)/
(root),我得到 HTTP 404 - The resource cannot be found.
如果我去例如 ://(url)/Overview
,它工作正常 .
我怎样才能让它像我想的那样工作?
1 回答
映射路线的顺序很重要,第一个匹配的路线获胜 . 这意味着即使没有资源,它也会匹配它将使用它的路由 .
Default
和SharedPages
路由的问题是它们相互冲突 . 您可能需要为其他控制器(如果存在)提供特定路由 . 另外一个选择是使用属性路由为其他控制器和基于约定的路由为您的根路由和错误随着控制器装饰相应