Override the default controller scaffold templates in Visual Studio 2019 and .NET 5.0

The real power of scaffolding in Visual Studio comes from the ability to override the templates which are used to generate the controllers and views. This gives us complete control of the C# and HTML which is emitted by the scaffolding process.

The templates for Visual Studio 2019 and .NET 5.0 are stored in C:\Users\USERNAME\.nuget\packages\microsoft.visualstudio.web.codegenerators.mvc\5.0.2 as shown below…

Where to find scaffold templates

We can update these templates directly in the above location but this is problematic as it is local to a developers machine and therefore not easily shared with other team members and because changes made here would affect all projects on the machine which may not be desired.

A better way is to copy the templates into our MVC projects like below so they can be checked into source control and shared across the team.

Required folder structure for custom scaffolding

This works as by convention Visual Studio will look for a Templates folder in the MVC project first before using the machine level folder.

Note… you may see build errors related to the templates you’ve just copied into your project before you first try to scaffold. These will go away when Microsoft.VisualStudio.Web.CodeGeneration.Design is installed which Visual Studio will do as part of the scaffold process.

Scaffolding multiple controllers at once from the command line

After you’ve customised your templates you can rescaffold your controllers one by one manually from the GUI, but a better way is to call the asp.net core scaffolding engine from a bat file.

One thought on “Override the default controller scaffold templates in Visual Studio 2019 and .NET 5.0”

Leave a Reply

Your email address will not be published. Required fields are marked *