How to do URL Rewrites with ASP.NET 2.0 3.0 3.5 on IIS6 and IIS7 and What is Wild Card Mapping

The Problem

Over the past several years I’ve found myself running into the same problem over and over so I thought I’d blog the solution so at least I don’t waste time figuring it out again.  So, when do you need this?  The answer for me is that I want to be able reference a web site without having to expose the underlying site structure.  For example, on the home page of my business, I want people to be able to type http://73rdstreet.com/Home and be taken to http://www.73rdstreet.com/HomeSite/Home.aspx.

The Symptom

You may see errors that say something like:

Server Error in Application … HTTP Error 404.0 – Not Found

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

MapRequestHandler StaticFile

And the screen may show something like this.

x

If this happens, read on.

Theory

The first thing to understand is that IIS by default will pass to the asp.net process only the requests that have a certain file extension.  That is, aspx,ashx,etc.  Basically, only file extensions that have a handler defined for them to be processed by.  Other URL’s that don’t meet the criteria are not passed to IIS.  This includes no file extension at all.  There is a good reason for this.  One, it makes processing of things like images (jpg’s, gif’s, etc.) faster because they do not every have to be processed through the asp.net worker process.  Secondly, it lowers the exposure of the asp.net worker process so that it is less likely to be compromised.

So, the first thing that has to be done is to tell IIS to pass all requests through using something called Wild Card Mapping.  Then, once this is done, the request comes through to the asp.net worker process regardless of what it is.  As we know, the place that we would have to process this is an HttpModule.  The reason is that since it’s not a page yet, we have no idea what to do with it.  Basically modules let you tap into the request at different stages.  To do the rewrite from ../Home to ../HomeSite/Home.aspx we want to tap into the Application_BeginRequest event.  The Context.RewritePath method is called at that point to force a new path based on what we want (hopefully not hard coded).

After the ReWritePath is set, the page is processed as if is going to the correct page.

How To Set Wild Card Mapping in IIS6

To Set Wild Care Mapping in IIS6 you need to do the following.

Run inetmgr and navigate to the Properties page of the website you want to set.

test 

Then, from the properties page, click the Configuration button as shown below.

t

Then, press the insert button on the configuration screen and see the following screen and then click on the insert button.

t[6]

Now, insert your asp.net isapi dll.  On my system, the file is here:  C:WINDOWSMicrosoft.NETFrameworkv2.0.50727aspnet_isapi.dll.  Make sure to uncheck the box "Verify that file exists".

t[9]

That’s it! Now, all requests will be processed through you asp.net pipeline so you will be able to intercept anything on the URL you want.  Be careful though, you may get more than you ask for!

How To Set Wildcard Mapping in IIS7

In IIS7 things are a little different.  First thing you need to do is unlock the config section "handlers". You do this by bring up a DOS prompt and entering the command:

C:WindowsSystem32inetsrv>appcmd.exe unlock config /section:system.webserver/handlers

Then, you can set your wildcard handler in your web.config file as follows.

Now, the default handlers will be executed in your web.config file, and of course, all the defaults for that are in the chain of files that inherits from.  For more details on that, see this FAQ: Configuration Files FAQs (web.config, machine.config…).

You may need to add the wildcard mapper handler to your web.config.  To do this, you would put the following in your web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="WildCard" path="*" verb="*" type="sampletype" resourceType="Unspecified" />
        </handlers>
    </system.webServer>
</configuration>

Now, you should be set. See the next section for a good method for actually doing the remapping, which is why we went down this path in the first place.

Implementing a URL ReWriter for Mapping ../Home to ../HomeSite/Home.aspx

So, as discussed in the theory section above, you could write your own code to map what you want to where you want it.  You could put in your global.asax some code for the Application_BeginRequest and make a big case statement for everything you want to do.  Well, as we know, that would give your code a bad smell and we don’t want that because soon, you will find yourself using cut and paste and other problematic crutches.

So, to avoid all that, and do what Scott Guthrie suggests, use the open source package UrlRewriter.NET.  It’s light-weight and configurable through a small section in your web.config. Before putting in the what to do, here are the steps to make UrlRewriter work in a very simple way (the way I use it on my company home page.

In your <System.web> of your web.config place a definition for a new config section where you will put your rewrites

<configuration>
    <configSections>
      <section name="rewriter" requirePermission="false" 
        type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter"/>

 

Then, put the module that actually does the work of the rewrite as described in the theory section above

<system.web>
   <httpModules>
     <add name="UrlRewriter" 
           type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
     </httpModules>
       ..

Then, further down in your web.config put

<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules>
    <add name="UrlRewriter"
         type="Intelligencia.U
 
And, Finally to actually do the redirect you need to put a new <rewriter> tag with a list of redirects in it.
 
<rewriter>
  <rewrite url="~/Home" to="~/pages/Home.aspx"/>
</rewriter>

That’s it!  You are done.  Hope this helps, or at least helps me the next time I’m searching for the same problem (for the 4th time at least).

References:

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. Great job man. Its works for me 2.0

  2. Thank you for posting this article!!!

  3. Rafi Ahmed says:

    Hi Petar,
    Very Nice article, I was suffer this issue from last couple of days.I already implemented URL rewriting with Intelligencia.UrlRewriter and its working fine when you run appliction from .net.But its not working when you make a virtual directory and run by IIS server.
    Now I did mapping with aspnet_isapi.dll file with(.*) extention.Great its working fine.But now i m not able to set Default page of my website here on IIS server. I set here Default.aspx and when i try to browse my website ,its not displaying and while i wirte like http://localhost/Mysite/default.aspx then its showing me the default page. So please tell me how i set my default page for my website in this scenario.

    Thanks in Advance,,,
    Rafi Ahmed khan

  4. santosh kakani says:

    I have SIngle line solution for this using

    please see this link

    http://myworkcodes.wordpress.com/2011/05/05/130/

    mark it as fixed if you got solution

    regards
    santosh kakani

  5. You made some decent factors there. I seemed on the internet for the issue and located most individuals will go along with along with your website.

  6. (Apologies to admin for triple post. Please retain this one)

    Minimalist Code for URL Mappings:
    [system.webServer]
    [modules runAllManagedModulesForAllRequests="true" /]
    [/system.webServer]

    [urlMappings enabled="true"]
    [add url="~/default" mappedUrl="index.aspx"/]
    [add url="~/login" mappedUrl="login.aspx"/]
    [add url="~/logout" mappedUrl="logout.aspx"/]
    [/urlMappings]

    http://ronniediaz.com/2011/04/06/simple-url-rewritingmapping-in-iis7/

  7. [code]

    [/code]

  8. There’s another alternative if your mappings are simple/static and/or you have a spare grunt to quickly and easily keep them updated without having to write a line of code.

    In web.config add:

    Under system.web add static mappings like so:

    Voila.

    Of course some scenarios require more complex mappings, but for most non-ecomm/non-web app sites and even blogs this solution would work np, be faster to maintain without requiring assembly publishes and is less error-prone.

    RD

  9. Could not load type ‘sampletype’ can you resolve the same.
    I tried entire step It is working with iis6 but while migrating IIS6 to IIS7 we are facing the problem.

  10. I found I was still getting 404 until I set the Integration mode to Classic from Integrated for the application pool the website was using, then it kicked in to life.

  11. hasan habib says:

    Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
    –>

    <!–
    The section enables configuration
    of the security authentication mode used by
    ASP.NET to identify an incoming user.
    –>

    <!–
    The section enables configuration
    of what to do if/when an unhandled error occurs
    during the execution of a request. Specifically,
    it enables developers to configure html error pages
    to be displayed in place of a error stack trace.

    –>

  12. hasan habib says:

    can u plz provide a sample web.config file to understand where to put
    above line u mention.
    i try buy got error.

    best regards

  13. This invests the opposition, and its struggle to replace the government, with apparent legitimacy, while undermining the legitimacy of the government under attack. ,

  14. Im just going to repest an earlier question, because I’m experiencing the exact same.

    I’m getting the following error:

    Could not load type ’sampletype’.

    What are the correct type and resourceType values to use for a basic mapping of * to the UrlRewriter module?

  15. Sign: umsun Hello!!! rcuwwymhyw and 2354ssgfhphzye and 9332I will try to recommend this post to my friends and family, cuz its really helpful.

  16. Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

  17. Help me !!!
    Problem with IIS 7.0 !!!
    Write in web.config this code but it’s do not work (((

    [system.webServer]
    [modules]
    [add name="FixURLs" type="FixURLs" preCondition="integratedMode" /]
    [/modules]
    [/system.webServer]

    [system.web]
    [httpModules]
    [add name="FixURLs" type="FixURLs" /]
    [/httpModules]
    [/system.web]

  18. Help me !!!
    Problem with IIS 7.0 !!!
    Write in web.config this code but it’s do not work (((

  19. Pete Hurst says:

    I’m getting the following error:

    Could not load type ‘sampletype’.

    What are the correct type and resourceType values to use for a basic mapping of * to the UrlRewriter module?

  20. This is interesting approach.
    I am using .net 3.5 sp1 on windows server 2003 and have turned on wildcard
    it is still giving 404

    bally
    http://filmjamr.com

  21. thank you

  22. http://forums.iis.net/t/1151311.aspx

    Re: trying to do a urlrewrite of ~/home to /Pages/Home.aspx with integrated mode
    Reply Delete Edit Favorites Contact Moderate
    URL rewrite module can easily do this kind of rewriting, however it requires that the hosting provider has it installed and enabled.

    If your hosting provider does not have official IIS URL rewriter module installed then an alternative solution is to use one of the an open source .NET url rewriting solutions such as URLRewriter.NET. In order for it to work with IIS 7.0 integrated pipeline mode, register the module within section as follows:





    The preCondition attribute is important here. Setting it to emtpy string ensures that the module will run for all requests, not just requests for managed handlers.

    http://ruslany.net

  23. Other related resources that might be useful:

    URL rewriting module for IIS7: http://blogs.iis.net/bills/archive/2008/05/31/urlrewrite-module-for-iis7.aspx

    How to build a managed module for IIS7 integrated pipeline (this renders wildcard mapping obsolete): http://learn.iis.net/page.aspx/366/developing-iis-70-modules-and-handlers-with-the-net-framework/ and http://learn.iis.net/page.aspx/170/developing-a-module-using-net/

Trackbacks

  1. [...] when you go to /hap/api/test in the browser? In IIS, make sure you have done the Wildcard Mapping (How to do URL Rewrites with ASP.NET 2.0 3.0 3.5 on IIS6 and IIS7 and What is Wild Card Mapping | Pet…) Reply With [...]

Your Comments

*

Protected with IP Blacklist CloudIP Blacklist Cloud

Follow

Get every new post delivered to your Inbox

Join other followers: