Configuring RazorEngine for ASP.NET Medium Trust

ASP.NET in Medium Trust does not allow direct instantiation of CodeDomProvider instances. This means we need to use ASP.NET's BuildProvider model to defer compilation to the build system. To do this, you need to add a reference to RazorEngine.Web to your project.

Step 1 - Wire up the RazorVirtualPathProvider

You need to register the RazorVirtualPathProvider to allow the BuildManager to make calls to virtual Razor file paths.

protected void Application_Start()
{
    HostingEnvironment.RegisterVirtualPathProvider(new RazorVirtualPathProvider());
}

Step 2 - Add the RazorEngine configuration section

There are a specialised set of compiler services for Medium trust scenarios. We need to use the WebCompilerServiceFactory which is used to create these services.

<configuration>
    <configSections>
        <section name="razorEngine" type="RazorEngine.Configuration.RazorEngineConfigurationSection, RazorEngine" requirePermission="false" />
    </configSections>

    <razorEngine factory="RazorEngine.Web.WebCompilerServiceFactory, RazorEngine.Web" />
</configuration>

Step 3 - Configure the BuildProviders

We map calls to virtual paths ending in ".csrzr" and ".vbrzr" to allow our BuildProvider to intercept and build the types. We don't use the Razor MVC file extensions (".cshtml", ".vbhtml") as we do not want to conflict with an existing MVC 3 application.

<configuration>
    <system.web>
        <buildProviders>
            <add extension=".csrzr" type="RazorEngine.Web.CSharp.CSharpRazorBuildProvider, RazorEngine.Web" />
            <add extension=".vbrzr" type="RazorEngine.Web.VisualBasic.VBRazorBuildProvider, RazorEngine.Web" />
        </buildProviders>
    </system.web>
</configuration>

You should now be able to make calls to parsing methods in your web application.

Last edited Jan 19, 2011 at 10:11 PM by AntarisZX, version 1

Comments

peter_guyette Jan 15, 2014 at 1:31 PM 
The documentation for the first step appears to be missing something, can not resolve RazorVirtualPathProvider

midnit Oct 31, 2013 at 3:14 AM 
Can you update this for the latest version?

albertoleonTis Sep 7, 2011 at 4:56 PM 
The element <buildProviders> shoulds be placed within <system.web><compilaton>:
See this resource: http://msdn.microsoft.com/en-us/library/h0e51sw9.aspx