Click here to Skip to main content
Email Password   helpLost your password?

Introduction

(ASP.NET, C#, Visual Studio 2005)

Hi folks; Recently, I built a custom Content Management Software for a website. The client wanted the page contents to be served from database by a page ShowContents.aspx?ContentID=XX.
The main requirements were as follows:

Solution

After a day's research, I came up with this really simple solution. I thought I should sum up the knowledge collected from various sources and make it public for everyone to benefit.
You can integrate following steps in to your existing ASP.NET project, or you can create a new one.

STEP 1

STEP 2

Using the code

// STEP 1 (ShowContents.aspx)

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// This page displays contents from a database for a ContentID. This file

// must contain the following line in it's Page_Load() event.

Context.RewritePath(Path.GetFileName(Request.RawUrl)); //needs System.IO


// STEP 2 (Global.asax)

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Following code goes in your Global.asax file, in the root directory of

// the project. This file captures the incoming requests' URL, gets the 

// Content ID of the content related to the URL and redirects the user to

// ShowContents.aspx?ContentID=XX. While the user still sees the requested 

// URL in the address bar.


    <%@ Import Namespace="System.IO" %>
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // If the requested file exists

        if (File.Exists(Request.PhysicalPath))
            { 
                // Do nothing here, just serve the file

            }
        // If the file does not exist then

        else if (!File.Exists(Request.PhysicalPath))
            {
            // Get the URL requested by the user

            string sRequestedURL = Request.Path.Replace(".aspx", "");
            
            // You can retrieve the ID of the content from database that is 

            // relevant to this requested URL (as per your business logic)

            int nId = 0;        
            ////// nId = GetContentIDByPath(sRequestedURL); \\\\\


           // The ShowContents.aspx page should show contents relevant to 

           // the ID that is passed here

            string sTargetURL = "~/ShowContents.aspx?ContentID=" + nId.ToString();

            // Owing to RewritePath, the user will see requested URL in the

        // address bar

            // The second argument should be false, to keep your references

        // to images, css files

            Context.RewritePath(sTargetURL, false);
        }
    }
//  That's all! :-) 

 

Hope this helps you save time on researching various sources. You might like to download the zip file containing a sample VS 2005 project.

Feedback is welcome and appreciated.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralProblem with styles
benny60
13:36 17 Oct '09  
Hi,

thanks for very good and simple solution of friendly url's. I have added it to my application and everything works fine until I put Context.RewritePath(Path.GetFileName(Request.RawUrl)); to page's Page_Load event. When I visit page with this code, I get page without styling. My stylesheets are in Theme in App_Theme folder and they are delivered to the page in Page_PreInit event:
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
Page.Theme = ConfigurationManager.AppSettings("theme").ToString
End Sub
Is there any solution to solve this problem?
GeneralRe: Problem with styles
Manu Agrawal
14:25 12 Nov '09  
Instead of the App_Theme folder, please try putting CSS files in just a plain folder called CSS in the root directory of your solution.
Questionimages and css file path
deching
20:45 17 May '09  
ciao everybody!
the example works very well...
but i cant see the images and css file... because.. path dosent change..
can u help me??

thanks
nicola
AnswerRe: images and css file path
Manu Agrawal
14:27 12 Nov '09  
Did you put those images and CSS in App_Theme folder? Please try moving them to a plain folder in the root directory of your solution.

Thanks.
GeneralAnother easy and efficient approach sample code
samardeep
22:04 6 Apr '09  
Hi..

I've found another working, easy and efficient example smaple code

Rewrite url sample code

cheers..

programmign techniques

GeneralFor Simplest Way of writing URL Rewriting
DotNetGuts
11:31 24 Jul '08  
I have wrote a article which explains how to write URL Rewriting with simplest example, step-by-step.
http://dotnetguts.blogspot.com/2008/07/url-rewriting-with-urlrewriternet.html[^]

DotNetGuts
"Lets Make Programming Easy"

Logon to www.DotNetGuts.2ya.com
Join Us @ DotNetGuts@YahooGroups.com

GeneralWhy Not Use UrlRewriter.Net?
nickyt
7:04 19 Jun '08  
Why not use the open source project UrlRewriter.Net (see http://urlrewriter.net). We used it very successfully at the company I worked at previously even though the site tanked big time. (Google Capazoo if you want to read about drama, controversy and laughs)

Later,
Nick


GeneralQuestion
Ashley van Gerven
17:36 17 Jun '08  
Just wondering why the second Context.Rewrite is necesary in the Page_Load? You mention it's for Postback, but how does it differ from the first rewrite;

Context.RewritePath("~/ShowContents.aspx?ContentID=11"); // in global.asax
..
Context.RewritePath("ShowContents.aspx"); // in ShowContents.aspx

Both calls are on Context object - is this a double up?



"For fifty bucks I'd put my face in their soup and blow." - George Costanza

GeneralDoesn't work!
adalbas
6:46 12 Jun '08  
Do I need to do anything in IIS to put this working?

I'm always served with a 404 error page from IIS!

Thanks in advance,
Adalberto
GeneralURL Rewriting Advice
atwalb
7:41 11 Jun '08  
I am contemplating using this on my site, has anyone used this and if so could you please provide some feed back and any issues you may have had. Would it be better to use this or the URL rewriter solution. My site is running in a web farm.
Newsimages and css not load on main page
shaan
22:58 11 May '08  
Nice article
I face one problem while rewrite url when i rewrite url css and image is not apply on my page i also write step1 line on page load of my main page but it's not working can u please give my some solution i am working on .net 2005 so on my local server how to configure iis.
Generalimages not working
Steve456
17:05 18 Mar '08  
Hi thanks for the post.

I have been working on this for a few hours and was pleased to see someone else was working toward a solution. The key for me is getting all the other resources (css, js, images, etc.) to map with those resources having relative paths.

I made a small vs project using your files and got your code to work fine. The only problem (and it's a big one of course) is that it doesn't look like other resources like css files and image files will work if they have relative paths.

For example when I added an image to both the Default.aspx file in your sample and also the same image (with the same path) to the ShowContents.aspx file, the image link is broken in the ShowContents.aspx file when it is requested via the rewritten url.

I'm sure I'm missing something. Any help will be appreciated!
GeneralRe: images not working
Manu Agrawal
11:47 15 Apr '08  
Hi,

1)
If you start your image path with a forward slash like this
"/images/abc.gif"
it will work from root directory.

2)
To use relative path you should also have configured your IIS to serve all requests from ASPNET.dll.
and

3)
You must have

System.IO.Context.RewritePath(Path.GetFileName(Request.RawUrl));

above line in the Page_Load() event of your main page.

If above does not help, please post your code here or email me.

Thanks for visiting this and leaving a comment.

Thanks

Manu Agrawal
GeneralExcellent
ultradream
5:20 5 Mar '08  
Hi
GOD Bless you
I have this in my dreams
ASP.NET SEF URL is Very Easier Than PHP & Apache
Never Forget you for this Article
Thanks a Lot!
Majid Smile
Generalwhy do i lose all my images and my css ?
greekhand
11:13 19 Sep '07  
why do i lose all my images and my css ????

Confused
AnswerRe: why do i lose all my images and my css ?
Manu Agrawal
11:51 19 Sep '07  
Hi,
Did you use the code in Step 1 above?
Please try step 1 and then let me know if you still get problems.

Thanks.
GeneralRe: why do i lose all my images and my css ?
greekhand
12:42 19 Sep '07  
well , i didn't do that before , now i did STEP 1 , but it still not working well ....
i just want ot point out that im using masterPages , but i guess it does not matter
Generali tried some stuff , got another question ...
greekhand
2:28 20 Sep '07  
i have to end the request url with .aspx or .html ... etc ??

i saw some urls that look like that : www.abc.com/abc (not like www.abc.com/abc.aspx)

but it seems that global. don't get the request if it looks like this : "www.abc.com/abc " .

any idea ???

about the css problem , i just use the full path (http://www ....) not like ~/css/general.css ....


Thanks .
GeneralRe: i tried some stuff , got another question ...
Manu Agrawal
3:35 22 Sep '07  
Till IIS 6, only asp.net requests (e.g. .aspx, .ashs, .ascx etc.) reach to global.asax file.

If you have permissions then, you can set IIS to handle .htm, .gif etc. requests by the process that handles asp.net.

1) Open IIS admin and right click on the website you want
2) select Properties > Home Directory > Configurations
3) select the .aspx from the list, click on Edit, and then copy the process path.
4) Cancel
5) click Add then paste this path in to the top box
6) type .htm in the extension box, uncheck Verify File exists
7) Click OK

Repeat this process for any other file extensions you want like .doc, .ppt etc.
GeneralRe: i tried some stuff , got another question ...
greekhand
5:17 25 Sep '07  
yeah , i got that by the time u reply ... but im in shared host account , can't do much


Thanks alot .
GeneralDotNetNuke friendly urls
Tommi G
16:03 16 May '07  
You should check out also DotNetNuke's friendly url implementation as it provides nice framework for such functionality. One feature that I personally like is the fact that you can create a friendly url with custom parameters like "/Home/MyPage/para1/50/para2/hello" so that the "para1" maps with value of "50" and "para2" maps with value "hello" and they are accessible through normal Request.QueryString -object.
GeneralPOST back problems
Andrei Rinea
11:55 8 May '07  
What if let's say you have a GridView with paging enabled and more than a page of rows in the GridView. In a "fake URL" page.

Now you will push on the "2"-nd page link on the GridView pager. Things will get a bit nasty then..
The Request will hold a different URL like "http://machine/fakeDir1/fakeDir2/ShowContents.aspx?querystring..."

I simply can't make it look nice (it works but after the first postback the URL in the browser looks ugly) after the first postbackFrown
NewsValidators and WebResource.axd in general
Andrei Rinea
6:12 3 May '07  
Watch out if you have a validator in any of your pages because they will request a javascript throught the WebResource.axd and if in "Application_BeginRequest" you treat this as a fake URL the page will not get its javascript but whatever you serve it..

Take care as this took me 1/2 hour to figure out .. Unsure
GeneralRe: Validators and WebResource.axd in general
Manu Agrawal
6:57 3 May '07  
Thanks for your feedback.
Really a useful tip.

Cheers.
AnswerRe: Validators and WebResource.axd in general
Andrei Rinea
7:09 21 May '07  
For now I just put the following line in Application_BeginRequest event handler:

if (File.Exists(Request.PhysicalPath) ||
Directory.Exists(Request.PhysicalPath) ||
Request.AppRelativeCurrentExecutionFilePath.ToLower().EndsWith(".axd"))
{
return;
}


Last Updated 21 Apr 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010