SIGN UP MEMBER LOGIN:    
ARTICLE

URL Rewriting in ASP.Net

Posted by Harshit Vyas Articles | ASP.NET Programming September 24, 2010
In this article we will see a method for URL Rewriting in ASP.Net.
Reader Level:
Download Files:
 

1.gif 

Introduction

Make our URL extension smaller using code and without writing too much in the web.config.

Recently I had the chance to work with URL rewriting. After doing some research I found some modules which we need to insert in our application and write mapped URLs or regular expression which was nice but we have to do that in many pages. So finally I invented my own code which is described below.

Code explanation

If you download my code then you can see that there is not too much code. I have written just a few lines of code in global.asax file which is as follows

void Application_BeginRequest(object sender, EventArgs e)
{
    string curruntpath = Request.Path.ToLower();
    curruntpath = curruntpath.Trim();
    bool isredirected = curruntpath.EndsWith(".aspx");
    bool isredirected2 = curruntpath.EndsWith(".html");
    bool isredirected3 = curruntpath.EndsWith(".jpg");
    bool isredirected4 = curruntpath.EndsWith(".jpeg");
    bool isredirected5 = curruntpath.EndsWith(".gif");
    bool isredirected6 = curruntpath.EndsWith(".png");
    // string atr = curruntpath.Substring(curruntpath.IndexOf("/"));
    if (!isredirected && !isredirected2 && !isredirected3 && !isredirected4 && !isredirected5 && !isredirected6)
    {
        HttpContext obj = HttpContext.Current;
        string finalURL = curruntpath + ".aspx";
        if (System.IO.File.Exists(Server.MapPath(finalURL)))
        {
            obj.RewritePath(finalURL);
        }
        else
        {
            obj.RewritePath("Error.aspx");
        }
    }
    if (curruntpath.EndsWith(".aspx"))
    {
        HttpContext obj = HttpContext.Current;
        obj.RewritePath("Error.aspx");
    }
}

First let me clarify what I have done with this code
  1. Make my page extension smaller
  2. I hid the aspx extension. For any request with this extension I simply redirect the page to my custom page error.aspx
  3. Also if any request comes for a page which is not available or has been moved I can show some relevant message but currently I have redirected them to the error.aspx page 
  4. Make the URLs friendly
Now let me explain the code:-

First thing is I have written my code in the Application_BeginRequest

It is the only event which fires every time when the page is going to call although you can also use the handler to achieve the same thing. 

First I have to make the list of items which are generally called when the page is loading like some images, css file and check for their request.

Here it is good to know that in Application_BeginRequest all the files are coming not only on one request all of the request comes so to avoid redirection of them I have made some conditions.

In the next step I am checking whether requested page is in my application or not. If yes then rewrite else redirect to error page.

Here URL will remain the same as end user has typed in his address bar.

See the below images

2.gif

Image 1

3.gif  

Image 2

Finally I want mysite's extension to be hidden so for all conditions that come with  the extension .aspx I redirect them to some other page.

4.gif

Image 3

So now URL rewriting has been completed.

Now, in your hyperlinks you just give the URL like...

<asp:HyperLink ID="HyperLink1" runat="server" NavigateURL="~/Default2"> Goto second page</asp:HyperLink>

Some other types to rewrite URL:-

By editing in the web.config file-

To do this you simply need to add these lines

<urlMappings>
        <add url="~/Default" mappedUrl="~/default.aspx"/>
</urlMappings>

In the web.config under <system.web> section here you need to add url and mapped url as you can see the above this feature is given by .net team from visual studio 2005. It is extreamly easy to rewrite url if you have to do this in small number of pages as it is not good idea to write this sentences for lots of pages.

Login to add your contents and source code to this article
share this article :
post comment
 

Thanks! This article good.

Posted by Dong Pham van Apr 24, 2012

I don't know the way to give "querystring" into url with your code .Can you tell me the way to decide?

Posted by viet vo quoc Nov 16, 2011

very good!keep sharing.

Posted by viet vo quoc Nov 16, 2011

i am using ii7.5 web server

Posted by siva kumar Feb 22, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Team Foundation Server Hosting
Become a Sponsor