Click here to Skip to main content
Click here to Skip to main content

Search engine friendly URLs in ASP.NET

, 27 Aug 2014 GPL3
Rate this:
Please Sign up or sign in to vote.
A basic guide for URL Rewriting

Introduction

URL rewriting can be one of the best and quickest ways to improve the usability and search friendliness of your site.

1. What is URL Rewriting?

1. On today’s modern internet, most of the websites are database driven. So, exchange of data between different pages is essential need of database driven websites. The query strings or GET parameters are very good approach to achieve this goal.

http://mayurlohite.com/page.aspx?productID=1

The above URL is dynamic and its sending the product id to page.aspx

2. So, what’s the problem with it?

Well, Maximum search engines (some exceptions – like Google) will not index any pages that have a question mark or other character (like an ampersand or equals sign) in the URL. So that means the page with question marks in URL is ignored by most of the search engines.

3. So, How search engine finds or index my page ?

There will be a solution of this problem, which is rewrite the URL to search engine friendly URL.

4. What is exactly the search engine friendly URL?

Lets take a look at below URL –

http://mayurlohite.com/page.aspx?productID=1 &Productnane=visual-studio

We have to convert above URL to following URL.

http://mayurlohite.com/displayproduct/1/visual-studio

Clearly a much cleaner and shorter URL. It’s much easier to remember, and vastly easier to read out. That said, it doesn’t exactly tell anyone what it refers.

5. How to convert Non search friendly URL to search friendly URL?
Its an easy task to converting URLs. Actually, I am working with ASP.NET C#. So, I will explaining how to achieve this with ASP.NET. I am using Global.axas Application_BeginRequest event handler.
Application_BeginRequest: is an event handler. It is part of the ASP.NET website system. The Application_BeginRequest method is executed on all requests handled by the ASP.NET run time.
First, this event handler is declared in a class that derives from HttpApplication. In such classes, the Application_BeginRequest method is automatically used when a request is received.

Using the code

1. First we are creating new website in visual studio 2010 for that open visual studio 2010. Click on File -> New -> Website

2. Select Visual C# from left and click on ASP.NET Empty Website template. In Bottom Web location Select File System and Type path to create new website.Give name “URLRewriteDemo” to website.

3. Now empty asp.net website is created there is nothing to display on solution so first we create Default.aspx page. To create new page right click on solution explorer click Add New Item. Select Webform from template and name it Default.aspx and click on add.

4. Add one new page to solution(same as Default.aspx) and name it page.aspx.

5. Now we want to send the Product ID and Product Name from Default.aspx to page.aspx So, We are using Query String to pass the values e.g. http://mayurlohite.com/page.aspx?productid=1&productname=visual-studio

6. we can access these values on page.aspx by Request.QueryString["productid"] and Request.QueryString["productname"] but this is not a SEO friendly pattern.

7. To solve this Add one Hyperlink field to Default.aspx and set NavigateUrl=”~/displayproduct/1/visual-studio”.

ASPX CODE FOR Default.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> URL Rewrite Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center;">
        <h1>
            URL Rewrite Demo</h1>
    </div>
    <br />
    <div style="text-align: center;">
        <h2>
            <asp:HyperLink ID="URLHyperLink" runat="server" NavigateUrl="~/displayproduct/1/visual-studio">URL Rewrite</asp:HyperLink>
        </h2>
    </div>
    </form>
</body>
</html> 

ASPX CODE FOR page.aspx  

<!DOCTYPE html PUBLIC &ldquo;-//W3C//DTD XHTML 1.0 Transitional//EN" &ldquo;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>URL Rewrite Demo</title>
</head>
<body>
    <form id="form1&Prime;" runat="server">
    <div style="text-align: center;">
        <h1>
            URL Rewrite Demo</h1>
    </div>
    <br />
    <div style="width: 500px; margin: 0 auto;">
        <table style="width: 100%;">
            <tr>
                <td>
                    &nbsp;
                    <asp:Label ID="Label1&Prime;" runat="server" Text="Product ID:"></asp:Label>
                </td>
                <td>
                    &nbsp;
                    <asp:Label ID="ProductLabel" runat="server"></asp:Label>
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;
                    <asp:Label ID="Label2&Prime;" runat="server" Text="Product Name:"></asp:Label>
                </td>
                <td>
                    &nbsp;
                    <asp:Label ID="ProductNameLabel" runat="server"></asp:Label>
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;
                </td>
                <td>
                    &nbsp;
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

8. In this example we are passing “displayproduct/1/visual-studio” to hyperlink[navigateurl] which is SEO friendly URL.

9. To write our rewrite rule we have to add Global.asax file in project. To add Global.asax right click on solution and click Add New Item and select “Global Application Class” from templates.

10. We are creating new Event Handler in Global.asax name it protected void Application_BeginRequest(Object sender, EventArgs e){}

CODE FOR GLOBAL.ASAX

<script runat="server">

void Application_Start(object sender, EventArgs e)
 {
    // Code that runs on application startup
 }

void Application_End(object sender, EventArgs e)
 {
    // Code that runs on application shutdown  
 }

 void Application_Error(object sender, EventArgs e)
 {
    // Code that runs when an unhandled error occurs  
 }

 void Session_Start(object sender, EventArgs e)
 {
    // Code that runs when a new session is started  
 }  

 void Session_End(object sender, EventArgs e)
 {

    // Code that runs when a session ends.
    // Note: The Session_End event is raised only when the sessionstate mode
    // is set to InProc in the Web.config file. If session mode is set to StateServer
    // or SQLServer, the event is not raised.  
 } 
 
 protected void Application_BeginRequest(Object sender, EventArgs e)
 {
    //Grab the URL for matching the pattern. Returns the current URL path.
    //e.g. http://example.com/displayproduct/1/visual-studio
    
    HttpContext incoming = HttpContext.Current;
    string oldpath = incoming.Request.Path.ToLower();

    //Declare variables for Query Strings.

    string productid = string.Empty;
    string productname = string.Empty;

    // Regular expressions to grab the productid and productname from the page.aspx
    //Here I am using regular expression to match tghe pattern.

    Regex regex = new Regex(@"displayproduct/(\d+)/(.+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
    MatchCollection matches = regex.Matches(oldpath);  
    
    //If Matches found then Grab the product id and name and rewrite it as our typical query string format.
    //e.g: http://example.com/page.aspx?productid=1&productname=visual-studio

    if (matches.Count > 0)
    {

     productid = matches[0].Groups[1].ToString();
     productname = matches[0].Groups[2].ToString();
     incoming.RewritePath(String.Concat("~/page.aspx?productid=", productid, "&productname=", productname ), false);
    }

 } 
 </script>

11. Now we are analyzing Application_BeginRequest(Object sender, EventArgs e) event handler.

A. The first two lines returns the current URL path.

HttpContext incoming = HttpContext.Current;
string oldpath = incoming.Request.Path.ToLower();

B. By using regular expression we can match the pattern of our requested URL with our rewrite URL. Means, when http://example.com/displayproduct/1/visual-studio is pattern matched with our regular expression and it rewrite the path to http://example.com/productid=1&productname=visual-studio

12. We can access the both query string parameter as same previous. e.g. Request.QueryString["productid"] and Request.QueryString["productname"] there is no change in traditional ASP.NET Query String system.

Hence, we achieve the SEO friendly URL by Global.asax Rewrite rule.

Points of Interest

Converting your traditional query strings to Search Engine Friendly URL behavior which gives tremendous benefits for search engine optimization also urls are easy to memorize.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

Mayur V Lohite
CEO Nullplex Software Solutions
India India
My name is Mayur Lohite. I am Programmer and Web Developer also I am Interested in Web Application Security and penetration. From a young age I’ve been fascinated with building web application and breaking it. So I have choose the Information technology as my career and completed the Degree in Information technology.
 
I’m a interested in operating and design of large-scale web applications/infrastructure and I’m interested in web application security also I am interested in some networking setting up servers, domains experimenting with clouds(well I am not professional at it)
 
I am a big fan of Anime series (Naruto) and also love to playing games. In the mean time I love to watching movies specially action movies.
 
Now I’m a white hat penetration tester. bug hunter and all out security freak by profession and passion. I’ve listed many websites Hall of fame e.g. Microsoft, Yahoo, Apple, Adobe
Follow on   Twitter   LinkedIn

Comments and Discussions

 
Questionhave some question in Url Rewritting PinmemberMember 1066075726-Sep-14 1:48 
AnswerRe: have some question in Url Rewritting [modified] PinprofessionalMayur V Lohite19-Oct-14 19:59 
QuestionYup PinmemberDuane Urban2-Sep-14 14:00 
SuggestionAnother Version Pinprofessionaladriancs27-Aug-14 21:28 
AnswerRe: Another Version PinprofessionalMayur V Lohite27-Aug-14 22:25 
GeneralMy vote of 5 PinprofessionalPratik Bhuva27-Aug-14 20:11 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun27-Aug-14 18:17 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.141022.1 | Last Updated 27 Aug 2014
Article Copyright 2014 by Mayur V Lohite
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid