RouteAttribute 破坏了我的默认路由
RouteAttribute broke my Default route
如果我将 [Route(Name = "WhatEver")] 应用于操作,我将其用作默认站点路由,我在访问站点根目录时收到 HTTP 404。
例如:
- 创建新的示例 MVC 项目。
添加属性路由:
// file: App_Start/RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(); // Add this line
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
添加路由属性
[RoutePrefix("Zome")]
public class HomeController : Controller
{
[Route(Name = "Zndex")]
public ActionResult Index()
{
return View();
}
...
}
现在,当您启动项目进行调试时,您将遇到 HTTP 错误 404。我应该如何将属性路由与默认路由映射一起使用?
当您启动站点时,在 App_Start 文件夹的 route.config 文件中设置了默认路由。它看起来像这样:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
如果您的家庭控制器中不再有 "index" 操作,该网站将徒劳地尝试将其作为主页并将 return 404。您可以更新您的 route.config 文件引用新主页。
对于使用带路由前缀的属性路由的默认路由,您需要将路由模板设置为空字符串。如果控制器已有路由前缀,您还可以使用 ~/
覆盖站点根目录。
[RoutePrefix("Zome")]
public class HomeController : Controller {
[HttpGet]
[Route("", Name = "Zndex")] //Matches GET /Zome
[Route("Zndex")] //Matches GET /Zome/Zndex
[Route("~/", Name = "default")] //Matches GET / <-- site root
public ActionResult Index() {
return View();
}
//...
}
也就是说,当在控制器上使用属性路由时,它不再匹配基于约定的路由。控制器要么全部基于属性,要么全部基于不混合的约定。
如果我将 [Route(Name = "WhatEver")] 应用于操作,我将其用作默认站点路由,我在访问站点根目录时收到 HTTP 404。
例如:
- 创建新的示例 MVC 项目。
添加属性路由:
// file: App_Start/RouteConfig.cs public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); // Add this line routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } }
添加路由属性
[RoutePrefix("Zome")] public class HomeController : Controller { [Route(Name = "Zndex")] public ActionResult Index() { return View(); } ... }
现在,当您启动项目进行调试时,您将遇到 HTTP 错误 404。我应该如何将属性路由与默认路由映射一起使用?
当您启动站点时,在 App_Start 文件夹的 route.config 文件中设置了默认路由。它看起来像这样:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
如果您的家庭控制器中不再有 "index" 操作,该网站将徒劳地尝试将其作为主页并将 return 404。您可以更新您的 route.config 文件引用新主页。
对于使用带路由前缀的属性路由的默认路由,您需要将路由模板设置为空字符串。如果控制器已有路由前缀,您还可以使用 ~/
覆盖站点根目录。
[RoutePrefix("Zome")]
public class HomeController : Controller {
[HttpGet]
[Route("", Name = "Zndex")] //Matches GET /Zome
[Route("Zndex")] //Matches GET /Zome/Zndex
[Route("~/", Name = "default")] //Matches GET / <-- site root
public ActionResult Index() {
return View();
}
//...
}
也就是说,当在控制器上使用属性路由时,它不再匹配基于约定的路由。控制器要么全部基于属性,要么全部基于不混合的约定。