36

How do I rewrite a URL in ASP.NET?

I would like users to be able to go to

http://www.website.com/users/smith

instead of

http://www.website.com/?user=smith
2
  • Scott Guthrie covers how to do this natively in .Net pretty extensively here. I've used the httpmodule approach and it works well. It's basically what ManagedFusion is doing for you. Commented Aug 5, 2008 at 13:28
  • For step by step explanation follow the below link: challadotnetfaq.blogspot.com/2011/08/… Commented Aug 3, 2011 at 12:26

3 Answers 3

25

Try the Managed Fusion Url Rewriter and Reverse Proxy:

http://urlrewriter.codeplex.com

The rule for rewriting this would be:

# clean up old rules and forward to new URL
RewriteRule ^/?user=(.*)  /users/$1 [NC,R=301]

# rewrite the rule internally
RewriteRule ^/users/(.*)  /?user=$1 [NC,L]
Sign up to request clarification or add additional context in comments.

2 Comments

A suggestion: I would adjust the first RewriteRule to look like ^/?users=(\w*) so that website.com/?users=smith&day=monday doesn't produce website.com/users/smith&day=monday
That is a good idea and totally supported in this .NET version. The original intent was to make my example compatible with mod_rewrite which doesn't support that syntax.
5

Microsoft now ships an official URL Rewriting Module for IIS: http://www.iis.net/download/urlrewrite

It supports most types of rewriting including setting server variables and wildcards.

It also will exist on all Azure web instances out of the box.

2 Comments

This looks interesting. Do you know if it will work on IIS6 and at what level in the network stack it sits?
This is a IIS7 and up solution only (its a module learn.iis.net/page.aspx/121/iis-7-modules-overview), for IIS6 you will need www.isapirewrite.com or www.urlrewriter.net, isapi rewrite seems like a stable commercial product for iis6
4

I have used an httpmodule for url rewriting from www.urlrewriting.net with great success (albeit I believe a much earlier, simpler version)

If you have very few actual rewriting rules then url mappings built in to .NET 2.0 are probably an easier option, there are a few write ups of these on the web, the 4guysfromrolla one seems fairly exhaustive but as you can see they don't support regular expression mappings are are as such rendered fairly useless in a dynamic environment (assuming "smith" in your example is not a special case then these would be of no use)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.