为什么我的命名路线不起作用?

Why doesn't my named route work?

标准 MVC 5 模板。
所以我试图理解并创建一个命名路由,如下所示:

<a href="@Url.RouteUrl(routeName: "myroute",  routeValues: new { code = "123" })">this link</a>

在家庭控制器中:

[Route("Home/DoIt", Name = "myroute"), HttpGet]
public ActionResult DoIt(string code)
{
  return View();
}

MvcAttributeRouting当然在RoutConfig.cs中启用了:

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  );
  routes.MapMvcAttributeRoutes();
}

因为如果未启用,将会得到:

A route named 'myroute' could not be found in the route collection. Parameter name: name

但我得到:

The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Home/DoIt

我做错了什么?

编辑:显然,我在 Route 属性上做错了,因为即使这样也不起作用:

  [Route("DoIt")]

[Route("Home/DoIt")]

两者都给我 404,无论请求 URL 是 http://localhost/Home/DoIt or http://localhost/DoIt

放置 MapMvcAttributeRoutes 行的 order 很重要。你有它在错误的位置。必须在默认路由之前调用。

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // Add this to get attribute routes to work
        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

路由的工作方式类似于 switch case 语句。 第一场 比赛获胜。但是,如果您将默认路由放在首位,它会将每个 URL 与 0、1、2 或 3 段匹配,并有效地覆盖这些长度的任何属性路由。

参考:http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx#enabling-attribute-routing

您是否尝试过直接从浏览器访问您的操作?我的意思是 YourHost/Home/DoIt。如果它也引发 404 错误,那么您的问题可能来自您的路由配置。

可能是您没有开启路由属性配置。检查以下内容: 来自 MSDN:

To enable attribute routing, call MapMvcAttributeRoutes during configuration.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();
    }
}