Url Routing is the process of reroute the http request, the reason behind it was to create a clean meaningful SEO friendly url.
For example, if you have a ecommerce website where you have thousands products, and you want to display each product details dynamically on a page called “product”.
the page may look like www.yourwebsite.com/product?pid=10
, then 11, 12 so on , all URL will look same except the change of product id value.
So the repetitive url does not make sense, and also search engine cannot understand the difference between each url.
Now with the help of routing, you can make the url to a meaningful url. for example,
you can make it like www.yourwebsite.com/product/10/white-thick-paper
or
www.yourwebsite.com/product/11/red-pen-for-kids
Before you start implementing routing, I assume you have basic understanding of Asp.net MVC Architecture.
Let's start with System.Web.Routing
In your App_Start folder, there is a file called RouterConfig.cs, this is how the code will look like
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 }); } }
Now, if you notice the above "RegisterRoutes" acutlly does the registration at Application_Start event of in Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
Now you need to understand how you can add a new routes.MapRoute(...)
in RouteCollection. One default implementation given in above
MVC applications use the ASP.NET routing system that decides how URLs map to controller,
action and optional parameter url:"{controller}/{action}/{id}"
, every time you add a new MapRoute with a new name
routes.MapRoute( name: "jobview", url: "jobs/job/{jobid}/{jobTitle}", defaults: new { controller = "jobs", action = "job", jobTitle = UrlParameter.Optional, jobid = UrlParameter.Optional });
Now you learn how to call this from your dynamic data, let’s say you have a collection of job, and for each job you want to create a dynamic SEO friendly URL
@foreach (vwJob j in jobList) {
<a title="@j.Title.ToLower()" href='@Url.RouteUrl("jobview", new
{
jobid = @j.jobId,
jobTitle = Util.GetSeoFriendlyName(@j.Title.ToLower())
})' >
@j.Title
</a>
}
Notice, href='@Url.RouteUrl()' to call the route map with name.
Have fun with Routing !
You should also learn Attribute Routing in Asp.net MVC using Asp.net Core framework.