RoutePrefix不适用于Asp.NET MVC

时间:2017-12-19 12:45:07

标签: c# asp.net-mvc routing attributes

RoutePrefix对我不起作用。

控制器

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

            return View();
        }
}

Rout Config

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而不是

  

无法找到资源。

<{1}}的

版本是5.2.3.0

2 个答案:

答案 0 :(得分:4)

我认为我找到了解决方案,你必须做以下更改

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视图就像这样

 <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 }
            );
        }

答案 1 :(得分:3)

routes.MapMvcAttributeRoutes();

在任何其他路线配置方法之前