Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use Attribute Routing in ASP.NET MVC

    • 0
    • 1
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 354
    Comment on it

    "Attribute Routing in ASP.NET MVC"

        Routing is a major concern in a MVC application, I have already discussed about the Routing Basics and Customization of routing.

    Please find below the links for reference:

    Basics of Routing
    Routing Customization

    Asp .Net MVC 5.0 introduced a new attribute named Routing attribute. It enables us to define routing on top of the controller action method.

    Before starting lets see how to Enable Attribute Routing:-

    To enable Attribute Routing we have to call the MapMvcAttributeRoutes method of the route collection class during configuration.

    Example:

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes(); 
            routes.MapRoute(
                   "Default", // Route name
                    "{controller}/{action}/{id}", 
                    new { controller = "Home", action = "about", id = UrlParameter.Optional } 
               );
        }
    }
    

    By using this attribute:

    1. We can provide different URLs for different Action methods.
    2. We can provide optional or default parameters.
    3. We can provide the prefix for the whole controller and can also override it.
    4. We can provide the default Route.
    5. We can also define the Area.

    Let us see in more detail:-

    1. Provide different URLs for different Action methods:

    Using Attribute Routing we can define different Routes to different Action Methods.

    Example:

    public class HomeController : Controller
    {
          [Route("Home")]
        public ActionResult Index()
        {
            return View();
        }
    
          [Route("AboutUs")]
        public ActionResult About()
        {
          return View();
        }
    
    
    }
    

    The Line [Route("Home")] and [Route("AboutUs")] defines the different Routes for the above two action methods. Now the URL for the Index() action method inside the Home Controller will be "http://{domain}/Home" and the URL for the About() action method will be "http://{domain}/AboutUs".

    2. Provide optional or default parameters:

    We also provide optional or default parameters in the URL pattern.

    For optional parameter we define a question mark (?") to the route parameter.

    Example:

    [Route("AboutUs/{ customerName ?}")] public ActionResult About(string customerName) { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(); }

    In this case the URL pattern may or may contain the parameter(s).

    For default parameters we write "parameter=value".

    Example:

          [Route("AboutUs/{ customerName =0036952}")]
       public ActionResult About(string customerName)
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }
    

    In this case if the URL pattern does not contain the parameter then the default value "0036952" will be provided.

    3. Provide the prefix for the whole controller and can also override it:

    Using "RoutePrefix" attribute we can set a prefix for the whole Controller.

    Example:

      [RoutePrefix("Home")]
    public class HomeController : Controller
    {
    
                 [Route]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }
    
    
           [Route("{ customerName }")]
        public ActionResult OtherTest(string customerName)
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }
    }
    

    Now for accessing the action methods inside the Home Controller we have to first write "Home" in the URL i.e "http://domain/Home". By this URL Index() action method will be called and if we provide some parameter such as "http://domain/Home/Harry" then OtherTest() action method will be called. If we don't write Home in the URL the default Route defined in the Route.Config File will be called.

    Now there may be the case for a particular action method inside the Home Controller where we don't want the Prefix, so for that we will override this prefix by using the '~' sign.

    Example:

         [RoutePrefix("Mvctest")]
    public class HomeController : Controller
    {
    
        [Route("~/NewMVCTest")]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }
    }
    

    As we can see that we have created a prefix in the Home Controller in the above code, so for calling the Home Controller we have to write "Mvctest" in the URL but as the Index() action method has overrided this prefix therefore it can be called by writing "NewMVCTest" in the URL.

    4. Provide the default Route:

    We can also define the default action method for the controller using the Routing Attribute.

    Example:

        [RoutePrefix("Home")]
         [Route("action=index")]
    public class HomeController : Controller
    {
    
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        } 
    
    
        public ActionResult NewMethod()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }
    }
    

    Now when we write Home in the URL by default the Index() action method is called and if we have to call the NewMethod() action method then we have to write "Home/NewMethod"

    5. Define Area:

    We can also define the Area by using RouteArea attribute.

    Example:

          [RouteArea("Test")]
          [RoutePrefix("Mvctest")]
          [Route("action=index")]
    
    public class HomeController : Controller
    {
    
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }
    }
    

    Hope it Helps.... Happy Coding..!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: