MVC 属性路由的最简单示例不起作用

The simplest example with MVC attribute routing doesn't work

我使用 VS2013 并通过向导创建了 MVC 应用程序。我还删除了所有额外的文件并具有以下内容:

1) RouteConfig.cs

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

2) HomeController.cs

public class HomeController : Controller
{
    [Route("Home/Index")]
    public ActionResult Index()
    {
        return View();
    }
}

3) Index.cshtml

@{
    ViewBag.Title = "Home Page";
}

Home page

我得到的页面有错误:

HTTP 403.14 - Forbidden

但是,如果我在浏览器的地址栏中手动添加 URL - Home/Index:

http://localhost:50600/Home/Index

页面出现。

我做错了什么?

从路线中删除 "Home",因为控制器名称 HomeController 已经以 "Home" 开始您的路线。如果您想更改 "Home" 前缀,可以向 HomeController class 添加一个属性来定义它。

此外,操作的默认路由名称将与操作名称相匹配,因此在这种情况下,您可以使用 [Route("")] 并且 url /Home/Index 会起作用。

我想我现在知道你的问题是什么了。您期望默认 url 显示您的 Index 视图 HomeController 但您没有设置默认路由。您可以通过在 RouteConfig.cs

中添加以下行来设置默认路由
config.Routes.MapRoute(
   name: "Default",
   routeTemplate: "{controller}/{action}",
   defaults: new { controller = "Home", action = "Index" }
);

或者,如果您只想使用属性路由而不与路由模板混合,您可以只添加默认路由,如下所示:-

config.Routes.MapRoute(
    name: "Index",
    url: "",
    defaults : new { controller = "Home", action = "Index" }
);

我的猜测是当你尝试这个时 url:

http://localhost:50600

它不起作用,因为您已经从路由配置中删除了默认路由。我不知道你是否自己删除了它,但是 RoutesConfig.cs 文件通常带有以下默认路由:

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

此代码确保如果用户未提供控制器或操作,则站点将默认为家庭控制器的索引操作(您可以在默认参数下看到)。这也可以解释为什么当您尝试这条路线时它会起作用:

http://localhost:50600/Home/Index.