What is Routing?
Routing is a very important concept in ASP.NET MVC which manages application the execution flow. It maps the requested URL to respective controller and action. Routing engine uses Route table for mapping.
System.Web.Routing is the namespace for route engine.
System.Web.Routing is the namespace for route engine.
In RouteConfig.cs file, present in App_Start folder is having routing rules which parse the URL and find out the corresponding Controller and Action.
For any request if subsequent Controller and Action will not be there then it returns a 404 HTTP status code which means "NOT FOUND".
Once your Routing rule is ready, you need to register this in Application_Start() method present in Global.asax file.
protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
RegisterRoutes is a function which is present in RouteConfig.cs file and this describes the routing rule for your application.
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 }
);
}
}
In the above lines of code name represents the route name and while giving the name always try to give a unique name.
URL, it represents the request pattern and defaults represents the by default controller and action name.
id = UrlParameter.Optional, It shows that id is optional. If you want to pass any value during the request using URL the you can pass the value.
Lets illustrate this with an example...
Request URL is, http://localhost:16787/Home/Index
In the above URL, Home is your controller and Index is the action. So when browser will get this request it will go to Home controller and in that Index action.
Lets modify the request URL like bellow
http://localhost:16787/Home/Index/101
Now controller is Home, action is Index and here there is a parameter which will get passed to the Action method.
For the above URL control will automatically passed to Home controller and Index action as they are defined default.
So
http://localhost:16787/Home/Index
http://localhost:16787/Home
http://localhost:16787
will perform the same action
You can define your own default controller and action. Also you can define your own rule for routing.
{
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 }
);
}
}
In the above lines of code name represents the route name and while giving the name always try to give a unique name.
URL, it represents the request pattern and defaults represents the by default controller and action name.
id = UrlParameter.Optional, It shows that id is optional. If you want to pass any value during the request using URL the you can pass the value.
Lets illustrate this with an example...
Request URL is, http://localhost:16787/Home/Index
In the above URL, Home is your controller and Index is the action. So when browser will get this request it will go to Home controller and in that Index action.
Lets modify the request URL like bellow
http://localhost:16787/Home/Index/101
Now controller is Home, action is Index and here there is a parameter which will get passed to the Action method.
For the above URL control will automatically passed to Home controller and Index action as they are defined default.
So
http://localhost:16787/Home/Index
http://localhost:16787/Home
http://localhost:16787
will perform the same action
You can define your own default controller and action. Also you can define your own rule for routing.
Example...
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{action}/{controller}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
For the above rule URL will be http://localhost:16787/Index/Home, because URL pattern changed to action/controller. If you will provide like http://localhost:16787/Home/Index, it will consider Home as an action and Index as a controller which will give HTTP 404 error.
You can modify your default route to any controller and to any action. Also you can customize your route rule as per your requirement.
Ignore Route
You can instruct your route engine not to handle request by ignoring routes.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
It will ignore all the request which is having ".axd" extension.
Attribute Routing
In MVC 5 you can use attributes for routing and this type of routing is called Attribute Routing.Normally in Convention-based routing, all the routing rules are present in RouteConfig.cs. So if you want to change some route rule, you need to modify all of them which may affect some where else in your code but attribute routing helps to define route as attribute is a very simple and easy way which is very nicely understandable.
How to use Attribute Routing
To use Attribute Routing in your, application first you to enable this. For enabling you need to call MapMvcAttributeRoutes in RouteConfig.cs.
You can use both Convention-based and Attribute routing in a single application.
Let's work with some examples:
You need to change your RegisterRoutes method as below.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
You can also combine both type of routing.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Note: Always call Attribute Route before Convention-based Route in RouteConfig.
Create a Products Controller and define the route as given below.
[Route("Products/GetProducts")]
public ActionResult GetProducts()
{
return View();
}
[Route("Products/ProductByID/{PID}")]
public ActionResult ProductByID(int PID)
{
ViewBag.ProductID = PID;
return View();
}
[Route("Products/EditPrductDetails/{PID}")]
public ActionResult EditPrductDetails(int PID)
{
return View();
}
}
In the above example you can find that "Products" is the common controller for all the method. So we can use a common prefix called [RoutePrefix].
[RoutePrefix("Products")]
public class ProductsController : Controller
{
[Route("GetProducts")]
public ActionResult GetProducts()
{
return View();
}
[Route("ProductByID/{PID}")]
public ActionResult ProductByID(int PID)
{
ViewBag.ProductID = PID;
return View();
}
[Route("EditPrductDetails/{PID}")]
public ActionResult EditPrductDetails(int PID)
{
return View();
}
}
There may some situation come where you don't want to use the RoutePrefix for a particular action and you need to have a different routing rule. For this you need to override the route prefix for that particular action.
You can use tilde(~) symbol for overriding RoutePrefix.
[RoutePrefix("Products")]
public class ProductsController : Controller
{
[Route("GetProducts")]
public ActionResult GetProducts()
{
return View();
}
[Route("ProductByID/{PID}")]
public ActionResult ProductByID(int PID)
{
ViewBag.ProductID = PID;
return View();
}
[Route("EditPrductDetails/{PID}")]
public ActionResult EditPrductDetails(int PID)
{
return View();
}
[Route("~/Orders/OrderProducts")]
public ActionResult OrderProdut()
{
return View();
}
}
Default Route
You can also define your default route. See the below example.
[RoutePrefix("Products")]
[Route("{action=Index}")]
public class ProductsController : Controller
{
public ActionResult Index()
{
return View();
}
}