Can I serve .html files using Razor as if they wer

2020-01-26 08:59发布

问题:

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?

回答1:

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");


回答2:

Call WebPageHttpHandler.RegisterExtension.

You may also need to register a custom WebPageRazorHostFactory to tell the Razor engine what to do with the file; I'm not sure.



回答3:

As this actually been resolved for use with VS2012 / .net 4.5. As using the examples above in a C#5 project I get no luck :(