Can I serve .html files using Razor as if they were .cshtml files without changing the extension of all my pages?

Kevin Lewis picture Kevin Lewis · Feb 24, 2011 · Viewed 7.3k times · Source

I manage a large asp.net site which has previously been converted from static html site to asp.net.

For several reasons (mainly SEO) we decided not to rename all the files to .aspx back when we originally converted the site. This was very easy to do by simply adding the buildProvider and httpHandler to the web.config.

<buildProviders>
  <add extension=".html" type="System.Web.Compilation.PageBuildProvider"/>
</buildProviders>

<httpHandlers>
  <add path="*.html" verb="*" type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>

Now I am upgrading the site to use Asp.net WebPages with Razor cshtml files. I can rename all the files if necessary, and use url rewriting to make the urls stay the same, however it would be much easier if I could just configure the web.config to tell it to parse .html files as if they were .cshtml.

I have searched around quite a bit, and could not find anything equivalent to the PageHandlerFactory for razor pages. It appears as though it is just an internal mechanism in the .net 4.0 ISAPI handler.

The site is currently running on Windows 2003 server and IIS 6. We will be upgrading to 2008/IIS 7.5 in the near future, but I'd prefer not to wait for that.

Is there any way to get the .html files to be parsed by razor as if they were .cshtml files?

Answer

Kevin Lewis picture Kevin Lewis · Feb 28, 2011

Thank you to SLaks for pointing me in the right direction, but it still took a few hours of digging in the MVC source to figure out the solution.

1 - Need to put RazorBuildProvider in web.config

<buildProviders>
    <add extension=".html" type="System.Web.WebPages.Razor.RazorBuildProvider"/>
</buildProviders>

And add System.Web.WebPages.Razor to assemblies if it isn't already there.

<assemblies>
     [...]
     <add assembly="System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>

2 - Add 2 lines in global.asax Application_Start() method

// Requires reference to System.Web.WebPages.Razor
System.Web.Razor.RazorCodeLanguage.Languages.Add(
    "html", new CSharpRazorCodeLanguage());

WebPageHttpHandler.RegisterExtension("html");