Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 385
John Doe Avatar asked Dec 19 '17 12:12

John Doe


People also ask

What is RoutePrefix in MVC?

Route Prefixes are nothing but the prefix for any route that we want to apply, all we need to do is to define the route prefix on a controller so that all the action methods inside it can follow the prefix. For example, [RoutePrefix("products")] public class ProductController : Controller.

Why we use attribute routing in MVC?

MVC 5 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application. The earlier style of routing, called convention-based routing, is still fully supported.


1 Answers

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 }
            );
        }
like image 162
Pranay Rana Avatar answered Sep 23 '22 09:09

Pranay Rana