tompazourek/RazorHtmlMinifier.Mvc5

Is it possible to support Razor @helpers in the /App_Code folder?

Closed this issue · 3 comments

This minifier seems promising. I was actually looking for something a bit more aggressive, but I understand that's not the goal of this project.

However, I noticed all Razor @helper functions from my /App_Code folder are not being minified. Is there any way to fix that?

I am not sure why the /App_Code files would be treated differently, I can't think of anything at the moment.

I would have to look at that closer and investigate when I find some more time.

If you want, you can clone the repository yourself and take a look in the source code to see if you can figure it out, there's a sample ASP.NET MVC project as well for testing. All the source code is really quite small...

So it turns out the Razor host factory configured in Web.config will not be used to compile Razor .cshtml files in the App_Code folder.

Right now, I don't think the Web.config file in the Views folder has any impact on App_Code files. This stackoverflow post mentions that namespaces configured in Web.config also don't apply to App_Code.

https://stackoverflow.com/questions/41985590/import-namespaces-automatically-into-all-cshtml-files-in-app-code-folder

I still wonder if there's a way to set it up so ASP.NET will use a custom decorated compiler for App_Code though. I've been digging for a while now, but have come up with nothing so far. The only notable thing I've found so far is: whatever is generating classes from App_Code, is using the ASP namespace.

image

I figured out I can use build providers to change what code will run when compiling .cshtml files.

<compilation debug="true" targetFramework="4.5">
    <buildProviders>
        <add extension=".cshtml" type="YourBuildProviderHere" />
    </buildProviders>
</compilation>

While implementing a build provider that minifies generated Razor code in App_Code files, I found this when decompiling WebRazorHostFactory:

if (virtualPath.StartsWith("~/App_Code", StringComparison.OrdinalIgnoreCase))
{
    host = (WebPageRazorHost) new WebCodeRazorHost(virtualPath, physicalPath);
}
else
{
    WebRazorHostFactory razorHostFactory = (WebRazorHostFactory) null;
    if (config != null && config.Host != null && !string.IsNullOrEmpty(config.Host.FactoryType))
        razorHostFactory = WebRazorHostFactory._factories.GetOrAdd(config.Host.FactoryType, new Func<string, Func<WebRazorHostFactory>>(WebRazorHostFactory.CreateFactory))();
    host = (razorHostFactory ?? new WebRazorHostFactory()).CreateHost(virtualPath, physicalPath);
    if (config != null && config.Pages != null)
        WebRazorHostFactory.ApplyConfigurationToHost(config.Pages, host);
}

This confirms my earlier suspicision that the factory configured in Web.config will not be used for App_Code.

I'm still working on getting it to work. I will share my findings here, and hopefully a pull request if I can get it to work.