Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get compile time errors in views using ASP.NET CORE

How can we get compile time errors in views and view components in Mvc6?

In MVC 5, it was simple to edit the .csproj file. How do we do it now?

like image 652
eadam Avatar asked Oct 31 '22 15:10

eadam


1 Answers

Answer for RC-1

  1. Create the following RazorPreCompilation class:
namespace YourApp.Compiler.Preprocess
{
    public sealed class RazorPreCompilation : RazorPreCompileModule
    {
        protected override bool EnablePreCompilation(BeforeCompileContext context) => true;
    }
}
  1. Places this class in {root}/Compiler/Preprocess.

enter image description here

  1. Add a call to AddPrecompiledRazorViews in your ConfigureServices method.
public void ConfigureServices(IServiceCollection services)
{
    // ... other code ...
    services
        .AddMvc()
        .AddPrecompiledRazorViews(GetType().GetTypeInfo().Assembly);
    // ... other code ...
}

As noted in other answers, when views are precompiled you lose the ability to change them while the application is running. Additionally, it seems that sometimes you have to do a rebuild on your project (as opposed to just a build) in order for new code changes to take effect. For example, correcting a typo in a Razor method call may still trigger a compilation error until you rebuild the project.

Update on Directives

If you'd like to have this run with preprocess directives, wrap them around the AddPrecompiledRazorViews call like this:

public void ConfigureServices(IServiceCollection services)
{
    // ... other code ...
    var mvcBuilder = services.AddMvc()
    
#if !DEBUG
    mvcBuilder.AddPrecompiledRazorViews(GetType().GetTypeInfo().Assembly);
#endif

    // ... other code ...
}
like image 153
Will Ray Avatar answered Nov 19 '22 10:11

Will Ray