Click here to Skip to main content
13,353,462 members (65,877 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

8.1K views
10 bookmarked
Posted 4 Oct 2015

URL Re-Writing with Global.asax

, 4 Oct 2015
Rate this:
Please Sign up or sign in to vote.
We will learn how to achieve URL Re-Writing using Global.asax file in ASP.NET to created SEO friendly URLs in our website or blog created with ASP.NET.

Introduction

Let's come back to the ASP.NET series again. We have had few more articles on ASP.NET before. This article is about making your website more SEO friendly. In the same topic, we have published a step by step tutorial on how to get dynamic meta tags and description from database.

URL Re-write using Global.asax

Let's start with simple steps. We will show you an example of our CMS project that is under construction. However, we will try to cover the basic steps from beginning to end to get the job done with screenshots.

Global.asax

As you add new item in your project in Visual Studio, you see a file type called Global Application Class.

Now, open the newly added Global.asax file and import a namespace called Web.Routing. Let's take a look at the code.

<%@ Application Language="C#" %>

<%@ Import Namespace="System.Web.Routing" %>

Now create a function with any convenient names with the below details. I have created a function with RegisterRoutes.

public static void RegisterRoutes(RouteCollection rColl)
   {
       rColl.MapPageRoute("DefaultWebsite",
       "{PageName}", "~/Default.aspx");

       rColl.MapPageRoute("DefaultDownloads",
       "Song/{SongID}/{SongURL}.aspx", "~/SongDetails.aspx");

       rColl.MapPageRoute("DefaultNews",
       "{Category}/{NewsID}/{NewsURL}.aspx", "~/NewsDetails.aspx");
   }

Let's discuss the code above:

DefaultDownloads is just the name. Song/{SongID}/{SongURL}.aspx song is just text and {SongName} & {SongURL} are two variables which we will replace with value in Browser's Address bar and use for searching in database. "~/SongDetails.aspx" is page which will do the query display data in users page according to PageRoutes.

In the CMS we are developing, we have currently three modules ready, so we have three RouteCollections named one for website, one for downloads and one for news. If you want to see a live working demo of the above code, we have Shared Hosting that is fully customized which is at Download Center.

You can click on any of the songs there and you can see dynamic URL which seems SEO friendly. You can add as much as you want but the work is not done yet. We still have to do something in Global.asax file. We have to set the above function execute on Application start event. Global.asax is designed to control the global settings like what to do when Application Starts or Ends or gets error, Session starts & Session Ends.

void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        RegisterRoutes(RouteTable.Routes);
    }

Now, you are all set on part of Global.asax. Lets move to the file which will handle the request.

Query on ASPX page:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
           GetDataFromURL();
    }

    void GetDataFromURL()
    {
        string SongName = Page.RouteData.Values["SongID"].ToString();
        if (SongName.Length>0)
        {
        int songID = Convert.ToInt16( SongName.Substring(SongID.LastIndexOf('-') + 1));
        GetData(songID);
        }
                else
        {
            Response.Redirect("~/Default.aspx");
        }
    }

But remember, to be so we have the Address set to correct location. Let's have a look at our logic that we have used to re-direct here.

<a href='<%# String.Format("Song/{0}/{1}.aspx",
Eval("SongID"),((string)Eval("SongURL")).Replace
(" ", "-"))%>' runat="server">
  <asp:Label ID="lblSongTitle" runat="server" 
  Text='<%#Eval("SongTitle")%>'></asp:Label></a>

Have a look at the above code, the code is in a similar format as in Global.asax file. Want to be reminded? Here is the code.

rColl.MapPageRoute("DefaultDownloads", 
"Song/{SongID}/{SongURL}.aspx", "~/SongDetails.aspx");

GetDataFromURL(): This function will perform all query from database and browser address bar. Page.RouteData.Values["SongID"].ToString(); : If you remember, we have put {SongName} in global.asax page earlier. This is the same. We have requested the value of SongName from browser.

GetData(songID): This is the same ID we will use to query and GetData is a function that will load data based on SongID.

Let's have a look at the working demo.

Have a look at the URL in the Address bar of the attached screenshot.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

John Bhatt
Founder P.Yar.B Complex
Nepal Nepal
John Bhatt is an IT Professional having interest in Web technology. He is Web Designer, Developer, Software Developer, Blogger and Technology Geek. Currently he writes his Blogs at Blog of P.Yar.B and various other Sites. He is Main author and founder of Download Center.
Contact Him at : Facebook | Twitter | Website | PRB - Blog.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Camilo Reyes6-Oct-15 4:50
professionalCamilo Reyes6-Oct-15 4:50 
GeneralRe: My vote of 5 Pin
John Bhatt6-Oct-15 4:57
professionalJohn Bhatt6-Oct-15 4:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 5 Oct 2015
Article Copyright 2015 by John Bhatt
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid