Attribute based routing

What Is ASP.NET MVC Routing ?

What Is Routing?

The MCV Routing is a pattern matching system that matches all browser’s incoming requests to the registered URL patterns residing in the RouteTable.


When the MVC application starts, it registers patterns to the RouteTable to tell the routing engine to give a response to the requests that match these patterns.


An application has only one RouteTable.

Routes can be configured in RouteConfig class.

Multiple custom routes can also be configured.

The route must be registered in Application_Start event in the Global.ascx.cs file.

Each MVC application has default routing for the default HomeController.

We can also set custom routing and the RouteConfig class.

The three segments that is important for routing is - {controller}/{action}/{id}


RouteConfig class

An example for Register Routes -
public class RouteConfig
{
    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 }
        );
    }
}

Register RouteConfig in Global.asax

protected void Application_Start() 

      AreaRegistration.RegisterAllAreas();  

      RouteConfig.RegisterRoutes(RouteTable.Routes);  

}  

Types of Routing

There are 2 types of Routing in MVC application

1.     Conventional or Traditional Routing (Using Routing Config)

2.     Attribute Routing (Available in MVC 5)

 

Conventional or Traditional Routing (Using Routing Config)

Conventional or Traditional Routing also is a pattern matching system for URLs that maps the incoming request to the particular controller and action method.

We set all the routes in the RouteConfig file.

RouteConfig file is available in the App_Start folder.

We need to register all the routes to make them operational.

 

Attribute Routing (Available in MVC 5)

What Is Attribute based Routing?
MVC 5 supports a new type of routing that called attribute routing. It is used to define routes.

Enable Attribute Routing - If you want to use Attribute Routing, you must enable it by calling MapMvcAttributeRoutes on the RouteCollection.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
      
        //Enables Attribute Routing
        routes.MapMvcAttributeRoutes();
    }
}

Defining a Route - A route attribute has to be defined on top of an action method or on the top of a controller.

The Example looks like,
public class HomeControllerBaseController
{
  [Route("User/GetUsers")]
  public ActionResult GetUsers(int Id)
  {
      return View();
  }
}

Custom Routes -
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name"User",
            url"User/{id}",
            defaultsnew { controller = "User"action = "Index"}
        );

        routes.MapRoute(
            name"Default",
            url"{controller}/{action}/{id}",
            defaultsnew { controller = "Home"action = "Index"id = UrlParameter.Optional }
        );
    }
}

What is RoutePrefix?

You may see that many routes have the same portion from their start; it means their prefixes are the same.

For example:

1.     Home/User

2.     Home/Teacher

Both the above URLs have the same prefix which is Home. So, rather than repeatedly typing the same prefix, again and again, we use RoutePrefix attribute.

This attribute will be set at the controller level.

 

See the below example,

 

    [RoutePrefix("Home")] 

    public class HomeController : Controller 

    { 

        [Route("User/{id= 1}")] 

        public string User(int id) 

        { 

            return $"User ID {id}"; 

        } 

  

        [Route("Teacher")] 

        public string Teacher() 

        { 

            return "Teacher’s method"; 

        } 

    }  

In the above code, RoutePrefix is set to controller level and on action methods, we don’t have to use Home prefix again and again.


What is MapRoute?

The MapRoute is use to add the new route in the Route collection.


ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^