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
Register
RouteConfig in Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
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 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.