Default Route and Route Name in Attribute Routing

Default Route

We will continue using the same example.The Route attribute can also be applied at the controller level to define a default action method. This route will apply to all actions within the controller unless a specific route is explicitly defined for a particular action, which would override the default controller-level route. Let's explore this with an example.


namespace AttributeRoutingDemoInMVC.Controllers
{
    [RoutePrefix("MyPage")]
    [Route("action = Index")]
    public class HomeController : Controller
    {
        // URL: /MyPage/
        public ActionResult Index()
        {
            ViewBag.Message = "Index Page";
            return View();
        }
        // URL: /MyPage/Contact
        public ActionResult Contact()
        {
            ViewBag.Message = "Contact page";
            return View();
        }
        // URL: /MyPage/About
        public ActionResult About()
        {
            ViewBag.Message = "About";
            return View();
        }
    }
}
                                        

Route Names

You can assign a name to a route to simplify URI generation for it. For instance, consider the following route:


namespace AttributeRoutingDemoInMVC.Controllers
{
    [Route("menu", Name = "mymenu")]
    public class MenuController : Controller
    {
        public ActionResult MainMenu()
        {
            ViewBag.Message = "Menu Page";
            return View();
        }
    }
}
                                        
You can create a link using Url.RouteUrl:

<a href=”@Url.RouteUrl(“mymenu”)“>Main menu</a>