KBD

Keith Devens .com

Friday, March 19, 2010 Flag waving
Darwin made it possible to be an intellectually-fulfilled atheist. – Richard Dawkins (The Blind Watchmaker)
← MySpace does 1.5 *billion* page views per day!Coding Horror: XP Automatic Update Nagging →

Daily link icon Monday, April 17, 2006

How to do clean URIs in your ASP.NET application

It's actually very simple to do clean URIs in an ASP.NET application. In your Global.asax file:

string root = "/rootofyourapp";

void Application_Start(object sender, EventArgs e){
    Dictionary<string,string> mapping = new Dictionary<string,string>();
    mapping[root+"/page"]=root+"/page.aspx";
    Application.Add("mapping",mapping);
}

void Application_BeginRequest(object sender, EventArgs e){
    HttpContext context = HttpContext.Current;
    string path = context.Request.Path;
    Dictionary<string,string> mapping =
        (Dictionary<string,string>)Application["mapping"];
    
    if(mapping.ContainsKey(path)){
        context.RewritePath(mapping[path]);
    }else{
        Response.AddHeader("Content-type","text/plain;charset=UTF-8");
        Response.Write("Invalid request: "+path+"\n\n");
        Response.End();
    }
}

And to forward all requests through to a single URI:

void Application_BeginRequest(object sender, EventArgs e){
    HttpContext.Current.RewritePath("~/Default.aspx");
}
← MySpace does 1.5 *billion* page views per day!Coding Horror: XP Automatic Update Nagging →

Comments XML gif

ryan wrote:

keith,

as a noob I have to ask - where does the second "void Application_BeginRequest" - in the aspx page itself, right?

∴ ryan | 6-Mar-2007 10:55am est | #10005

Keith (http://keithdevens.com/) wrote:

It's not a second, it's an alternative to the first.

Keith | 6-Mar-2007 1:28pm est | http://keithdevens.com/ | #10006

Bill wrote:

Keith,
I am working on a social networking project which allows users to create "URLs" to get directly to their profile pages (just like myspace does). I am writing the redirection code in the global.asax file in the application_beginrequest code block. I started off with some basic code to get the hang of redirecting the request.

void Application_BeginRequest(object sender, EventArgs e)
{
//Profile URL Check

if (string.Compare(this.Request.Url.AbsolutePath, "/bill", StringComparison.OrdinalIgnoreCase) == 0)
{
this.Response.Redirect("/profile_viewprofile.aspx?friendid=1", true);
}
}

Then it hit me. This method is fired for EVERY request including the css, any js files am using and of course all images.

I also realized that I don't want to let people surf to folders like /images, /bin, etc. So I created a filter list of folders that are part of my app.

Since their profile data is in SQL I will need to check the db to see if the "path" they are supplying matches with a profile. If it does I will then send the user to the view profile screen with a querystring paraemeter for the their friendid.

I shortcutted soem of the decision points and app layout but here is my question, is there a better way to do this type of redirection?

I am concerned that using the application_beginrequest method is going to have a huge performance hit on my application since EVERY request would have to be checked in a sense.

∴ Bill | 21-Jun-2008 3:04pm est | #10702

Keith (http://keithdevens.com/) wrote:

Well, your application requires that you check your URIs against a database. The main reason the efficiency of your solution concerns you seems to be that you didn't want the paths to static files to be checked against the db.

The way mod_rewrite handles this is it does a filesystem lookup (see this post for an example) to make sure it's not the path to an actual file before it tries to match regular expressions against it. You can do the same thing and do a quick filesystem check before you start doing db lookups.

I wouldn't be concerned about the efficiency of overriding Application_BeginRequest to interpret URLs. That event gets fired regardless, and all you're adding is one more db lookup to the number of db lookups you're already doing in your app. However, if you're using that to do redirects (as you show above) instead of serving a page to the user directly, then yes that's a performance hit of another request to the web server.


On second thought, since mod_rewrite processing happens at the web server level, and this type of URI processing happens at the application level, it'll necessarily be less efficient than the way Apache does things if the code has a chance to be given the URIs to files that are to be served statically by the web server. Yet another reason not to use Microsoft technologies for anything nifty.

However, lots of applications use actual code to serve images and such... it's just a straight binary dump of filesystem contents to the network. It's not so bad, compared to just letting the web server handle it, especially if your language is compiled like C# is. Or like you said, maybe you can configure the web server so that your static files are never checked against your above URI code.

Keith | 22-Jun-2008 11:23am est | http://keithdevens.com/ | #10703

Danny wrote:

is it possible to create something like

http://mywebsite/ViewProfile.aspx?UserName=joe

becomes this

http://mywebsite/joe

using ASP.NET

∴ Danny | 12-Aug-2008 9:40am est | #10757

Dave wrote:

Thank you for this post keith, it helped me a lot!!!

∴ Dave | 18-Sep-2008 7:32pm est | #10829

Feel free to post a comment below. Please see my comment policy.

Formatting Rules (No HTML):

  • **bold**, *italic*, _underlined_, --strikeout--
  • "text"="url" creates a link, and URLs are auto-highlighted
  • Blockquote: Like e-mail, begin paragraph with > (greater-than sign)
  • Lists: begin paragraph with *,-, or + (unordered), or # (ordered)
  • Code block: ?!code:language=perl|php|sql|javascript|etc.{\n}...{\n}?!/code

:
(will be your IP address if blank)
: (optional)
(Will not be shown on site)

: (optional)
:

March 2010
SunMonTueWedThuFriSat
 123456
78910111213
14151617181920
21222324252627
28293031 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 2 posts

Recent comments XML

I hate ASP.NET

I hate ASP... I was doing wonders​with PHP, then suddenly one of my​clients...

Johnies: Mar 17, 6:14am

Quantum physics and free will

I knew you were going to say that....

Tom Massey: Mar 15, 9:26pm

Generated in about 0.14s.

(Used 8 db queries)