Default Route and Route Name in Attribute Routing

Default Route and Route Name in Attribute Routing

In this article, I will discuss the Defining Default Route and Route Name using Route Attribute in ASP.NET MVC application. We are going to work with the same example that we started in Attribute Routing article of this article series. Please read Attribute Routing before proceeding to this article.

Default Route:

You can also apply the Route attribute on top of the controller (i.e. at the controller level), to capture the default action method as the parameter. That route would then be applied on all actions in the controller; unless a specific Route has been defined on a specific action, overriding the default setting on the controller.

Let’s understand 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 specify a name for a route, in order to easily allow URI generation for it. For example, for the following route:

namespace AttributeRoutingDemoInMVC.Controllers
{
    [Route("menu", Name = "mymenu")]
    public class MenuController : Controller
    {
        public ActionResult MainMenu()
        {
            ViewBag.Message = "Menu Page";
            return View();
        }
    }
}

You could generate a link using Url.RouteUrl:

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

SUMMARY

In this article, I try to explain the Defining Default Route and Route Name in ASP.NET MVC application. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *