RouteAttribute破坏了我的默认路由 [英] RouteAttribute broke my Default route
问题描述
如果我将 [Route(Name ="WhatEver")] 应用于操作(用作默认站点路由),则在访问站点根目录时会收到HTTP 404.
If I apply [Route(Name = "WhatEver")] to action, which I use as Default site route, I get HTTP 404 when accesing site root.
例如:
- 创建新的示例MVC项目.
-
添加属性路由:
- Create new sample MVC project.
Add attributes routing:
// 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 }
);
}
}
添加路由属性
Add routing attributes
[RoutePrefix("Zome")]
public class HomeController : Controller
{
[Route(Name = "Zndex")]
public ActionResult Index()
{
return View();
}
...
}
现在,当您启动项目进行调试时,将出现HTTP错误404.我该如何在默认路由映射中使用属性路由?
And now, when you start your project for debuging, you will have HTTP Error 404. How should I use attribute routing with default route mapping?
推荐答案
对于使用带有路由前缀的属性路由的默认路由,您需要将路由模板设置为空字符串.如果控制器已经具有路由前缀,也可以使用~/
覆盖站点根.
For default route using attribute routing with route prefix you need to set the route template as an empty string. You can also override the site root using ~/
if the controller already has a route prefix.
[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();
}
//...
}
也就是说,在控制器上使用属性路由时,它不再与基于约定的路由匹配.控制器要么全部基于属性,要么全部基于约定,不要混用.
That said, when using attribute routing on a controller it no longer matches convention-based routes. The controller is either all attribute-based or all convention-based that do not mix.
这篇关于RouteAttribute破坏了我的默认路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!