ASP.Net MVC | Mapping Static Files To MVC Controller

There are times, where we are working on projects that include migration of the websites with legacy technologies to the newer technologies. One of the requirement is to make sure, we some how map old URLs to new pages, so as to prevent unpleasant error pages to users who have bookmarked URLs from old website. However, other thing to keep in mind is that the old URLs indexed by Search Engines aren’t left completely broken.

ASP.Net MVC has feature where we can map the custom URLs to the MVC controller and actions. But this is limited to extension less URLs. Today we will see how to map URLs with the extensions (.html, .php, .asp, .aspx, etc.) or static files to MVC controller and actions.

I created a sample MVC project using Visual Studio. I have one controller (HomeController) with 3 actions (Index, About and Contact) in the sample project. Website is accessible using following URLs:

Home :

Home ASP.Net MVC

Contact :

Contact ASP.Net MVC

About :

About ASP.Net MVC

My requirement was simple, to map following legacy URLs to new MVC Pages/Actions:

  • index.html >> Home
  • contact.html >> Contact
  • about.html >> About

Step 1 : Add following HTTP Handler Mapping to web.config under system.webServer/handlers node section:


<system.webServer>
    <handlers>
      <add name="StaticToMVCHandler" path="*.html" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>

Step 2: Map the html routes to MVC controller and actions in RouteConfig.cs file:


routes.MapRoute(
	name: "StaticHome",
	url: "index.html",
	defaults: new {controller = "Home", action = "Index"}
	);

routes.MapRoute(
	name: "StaticAbout",
	url: "about.html",
	defaults: new {controller = "Home", action = "About"}
	);

routes.MapRoute(
	name: "StaticContact",
	url: "contact.html",
	defaults: new {controller = "Home", action = "Contact"}
	);

When you try to hit html URLs, you will be presented with new MVC developed website pages:

Home :

Home html

Contact :

Contact html

About :

About html

System.Web.Handlers.TransferRequestHandler is only applicable if the IIS Application Pool is having Managed pipeline mode as Integrated. For Classic mode, you need to apply following HTTP Handler Mappings:


<system.webServer>
    <handlers>
      <add name="StaticToMVCHandler" path="*.html" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" />
    </handlers>
</system.webServer>

In this example I have implemented routing for the html files. Furthermore one can map routes for php, aspx, asp, etc. files to MVC Controller and Actions.

If you aren’t familiar with ASP.NET MVC extensionless URL mappings, then read more about it here

Leave a Reply

Your e-mail address will not be published. Required fields are marked *