This post is about customizing the scaffold templates controllers and views in ASP.NET Core. We can achieve this by simply modifying the templates in this folder -
%USERPROFILE%\.nuget\packages\microsoft.visualstudio.web.codegenerators.mvc\6.0.6\Templates (the number 6.0.6 will change based on the SDK version) - but if we modify the template files in this folder it will impact the whole system and we can’t share the templates with other developers. So we can create a folder with name
Templates in the ASP.NET Core MVC project - while scaffolding, Visual Studio and
dotnet-aspnet-codegenerator global tool will first check this folder in your project and if it is available it will use the templates from this folder.
For this demo I am using customizing
Views. To do this first we will create a project in Visual Studio or from command line. Next we need to create a folder with name
Templates in the project root. And copy the
ViewGenerator folders from
Next I modified
EmptyController.cshtml and I added two more action methods, like this.
Due to some issues with the latest .NET Core release / VS 2022 release the Add New Item dialog is not working with this approach. If you’re using an old version of Visual Studio this will work. So I am using the
dotnet-aspnet-codegenerator global tool to generate the controller / view. To use this, we need to install this tool first - using this command -
dotnet tool install -g dotnet-aspnet-codegenerator and next we need to add reference of
Microsoft.VisualStudio.Web.CodeGeneration.Design nuget package to the project using the command -
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design.
Now we can scaffold the controller using the command
dotnet-aspnet-codegenerator controller -name ExampleController -outDir Controllers --no-build - if you notice, I included
--no-build flag otherwise the command will fail sometimes. If you want to avoid including this flag, you can exclude the
Templates folder by right clicking on the folder and choose
Exclude from Project if you’re using Visual Studio. Or we can modify the project file like this.
This will generate a controller with name
ExampleController with the following content.
We can use the same approach for Views as well. Here is an example of .NET Core scaffold templates for web application with MVC and RazorPages - Scaffold Templates for UI for ASP.NET Core by telerik.
Happy Programming :)