RoutePrefix对我不起作用。

Controller

[RoutePrefix("example-name")]
public class HomeController : Controller
{
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
}

路由配置
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();
}

索引页
 @Html.ActionLink("click me", "index","example-name");

我已经完成了所有基本步骤,但是我却没有收到404


System.Web.Mvc.dll的版本是5.2.3.0

最佳答案

我想我找到了解决方案,您必须进行以下更改

1.您错过的最重要的事情是:如果为控件指定RoutePrefix属性,则需要为操作指定Route属性。

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

          [Route("About")]
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }
}

2.你的html View 是这样的
 <li>@Html.ActionLink("hometext", actionName: "Index", controllerName: "hometest")</li>

3.将routes.MapMvcAttributeRoutes();移到MapRoute之前,如下所示。
   public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

10-08 07:19