Updated on Kisan Patel
This tutorial will explain you how to rewrite url to make it SEO friendly or user friendly in asp.net web form application.
TO re-write the URL, we need to register the URL routes into the Application_Start
event into Global.asax file. To do that we need to use System.Web.Routing
namespace.
using System; using System.Web.Routing; namespace WebRoutingDemo { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { RegisterRouotes(RouteTable.Routes); } void RegisterRouotes(RouteCollection routes) { routes.MapPageRoute("Details", "Details/{FirstName}/{Id}", "~/Details.aspx"); } } }
Lets take one example to understand how url routing work in asp.net web form application. Open Global.asax.cs file (If Global.asax file does not exist then Right click project solution => Add => New Item… => From Web Select “Global Configuration File” => click Add and it will add Global.asax file in your project) and add the below route inside Application_Start event.
using System; using System.Web.Routing; namespace WebRoutingDemo { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { RegisterRouotes(RouteTable.Routes); } void RegisterRouotes(RouteCollection routes) { routes.MapPageRoute("Details", "Details/{FirstName}/{Id}", "~/Details.aspx"); } } }
Next, open default.aspx page and add the below hyperlink.
Default.aspx
<a href="<%= WriteUrl("Kisan","54") %>" title="Show Details">Show Details</a>
Here, we have used WriteUrl method that accepts “FirstName” and “Id” parameter and generates url as shown in below code.
Default.aspx.cs
/// <summary> /// Writes the URL. /// </summary> /// <param name="firstName">The first name.</param> /// <param name="autoId">The auto id.</param> /// <returns></returns> protected string WriteUrl(string firstName, string Id) { return GetRouteUrl("Details", new { FirstName = firstName, Id = Id } ); }
Next, Open Details.aspx page add the below code.
Details.aspx
<form id="form1" runat="server"> <div> Name: <asp:Label ID="lbl_Name" runat="server"></asp:Label> <br /> Roll No.: <asp:Label ID="lbl_rollNo" runat="server"></asp:Label> </div> </form>
Details.aspx.cs
using System; namespace WebRoutingDemo { public partial class Details : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lbl_Name.Text = RouteData.Values["FirstName"] as string; lbl_rollNo.Text = RouteData.Values["Id"] as string; } } }
In above code, we can retrieve the route parameters coming into this page as URL using RouteData
object.
Demo