Sunday, September 17, 2006
Extending the URL Rewriting in ASP.NET
ASP.NET provides very limited support to achieve this out of the box – Scott Mitchell has already written a very neat implementation in his article URL Rewriting in ASP.NET where we can define mappings using Regular Expressions as follows.
I chose to extend this solution where I could define URLs which I don’t want to be re-written. Luckily, doing that was quite easy -- now I am able to define the web.config in the following manner.
I can either add a complete URL that I want to be excluded or better yet using regular expression I can add a group of URLs that contain the suffix 'Form.aspx' to be excluded from being rewritten.
At this point, if you haven’t read the article already, I suggest you read it first here. To do the above all I needed to do was to create two classes 'RewriterExceptions.cs' and 'RewriterExceptionCollection.cs' where the above
I also needed to add the following into the 'RewriterConfiguration.cs' class.
public RewriterExceptionsCollection Exceptions
exceptions = value;
And add a private instance of 'RewriterExceptionsCollection' class.
private RewriterExceptionsCollection exceptions;
Then in the 'ModuleRewriter.cs' module I needed to add the following block.
bool ExemptURL = false;
RewriterExceptionsCollection exceptions = RewriterConfiguration.GetConfig().Exceptions;
for(int i = 0; i < exceptions.Count; i++)
string excludeurl = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, exceptions[i].ExcludeURL) + "$";
Regex re = new Regex(excludeurl, RegexOptions.IgnoreCase);
string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, exceptions[i].ExcludeURL));
ExemptURL = true;
In the code above, I first get all the URLs, iterate through the collection and check to see if the current URL matches those that need to be excluded. I simply rewrite the URL to itself and set a Boolean value, I then check the Boolean in the code that follows which handles rewriting Rules block.
That’s all that needs to be done. You saw above that with few minor additions I was able to quickly extend Scott Mitchell’s solution and add support to exclude URLs from being rewritten.