Saturday, February 8, 2014

Url rewriting in ASP.NET using C#

In web tech URL rewriting is a vital thing for SEO(Search Engine Optimization). Not only for SEO its also important for the security reason. So we will take a look over this URL rewriting in ASP.NET using C# and Global.asax. Its nothing but a class inheriting System.Web.HttpApplication

Open a project and make some page according to your requirement and add a Global.asax file along with this project. To add this go to Add New Item and add Global.asax.

In the Global.asax.cs file you can see there are pre-written  seven methods named..


So apart from all these methods write a new method named RegisterRoutes with parameter RouteCollection routeCollection. To know more about RouteCollection  click here.

public static void RegisterRoutes(RouteCollection routeCollection)
        {
            /*This Part is for Routing of pages*/
            routeCollection.MapPageRoute("RouteForSuzainindex", "Default", "~/Default.aspx");
            routeCollection.MapPageRoute("RouteForSuzainAbout", "About", "~/About.aspx");
            routeCollection.MapPageRoute("RouteForSuzainContact", "Contact", "~/Contact.aspx");
            routeCollection.MapPageRoute("RouteForSuzainSchedule", "Schedule", "~/Schedule.aspx");
        }

Whatever your page name is just replace it by the name you want to show in this method. And call this method from Application_Start method.


protected void Application_Start(object sender, EventArgs e)

        {
            // Code that runs on application startup
            // Call the method to rewrite URL
            RegisterRoutes(RouteTable.Routes);
        }


And in the web application page write this code in the Page_Load event.

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string pageUrl = Request.Url.AbsoluteUri.ToString();
            if (pageUrl.Contains(".aspx"))
            {
                Response.Redirect(pageUrl.Replace(".aspx", ""));
            }
        }
    }

First its getting the page url using Request.Url.AbsoluteUri.ToString() and then searching for the .aspx extension and then replace the .aspx extension in the url by blank space. And your URL rewriting is complete. "AbsoluteUri" will return the full URL of the web page which is running.




0 comments:

Post a Comment

Popular Posts

Pageviews