Custom View Engine

In ASP.NET MVC, every controller can have multiple Action functions and each Action’s result is likely to be View. View Engine does the view render task. We will look the whole View Result Execution Process first.

The diagram above shows the framework will choose the default View path to run. If it does not find View in the default path, then it will find View in the second default path which set.

When the project architecture needs to adjust, View in some conditions may also have to change its default path to the new path based on the new project architecture needs. We can achieve this by Customizing View Engine. This article will introduce how to customize view engine in both ASP.NET MVC and ASP.NET CORE framework.

ASP.NET CORE

Add the above code in ConfigureServices method which is In StartUp.cs. Remember in AddRazorOptions method we have to use Insert rather than Add if you want your new View path has higher priority than the default path in selection. Use Insert will set your path before the default paths. However if you use Add method, your path will add after the default ones.

Add your cshtml file in the Theme folder, then you shall see the webpage below after you execute the process.

ASP.NET MVC

Create your Custom View Engine class. If you want your view to be razor type, then let your new view engine class inherit RazorViewEngine class.

Then add the code above in Global.asax class just like the one you did in ASP.NET CORE.

Appropriate use custom view engine help to build the project architecture that the develop teams want. Custom View Engine is not a hard topic. Asp.NET MVC provides many mechanisms for develops to customize the framework structure they want, this helps to achieve the team’s goal and application.