简体   繁体   中英

RoutePrefix does not work Asp.NET MVC

RoutePrefix does not work for me.

Controller

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

Index Page

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

i have complete all the basic steps, however i am getting 404 not

The resource cannot be found.

version of System.Web.Mvc.dll is 5.2.3.0

I think I found solution , you have to do following changes

1.most important thing you miss is : you need to specify Route attribute for the action if you specify RoutePrefix attribute for the control.

 [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.your html view like this

 <li>@Html.ActionLink("hometext", actionName: "Index", controllerName: "hometest")</li>

3.move routes.MapMvcAttributeRoutes(); before MapRoute as below.

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

Put

routes.MapMvcAttributeRoutes();

before any other routes configuration methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM