Check out my book "Hands-On RESTful Web Services with ASP.NET Core" available on Amazon or Packt.

.NET Core: Customize view paths

.NET Core: Customize view paths

Download from github

Intro

The .NET Core is finally released ūüôā !! ¬†I wrote about .NET Core a lot of times:

Future of ASP.NET is open source and cross platform

Introducing ASP.NET 5 on Ubuntu

Introducing vNext and MVC6

What is .NET Core?

ASP.NET Core is a lean and composable framework for building web and cloud applications. ASP.NET Core is fully open source and available on GitHub. ASP.NET Core is available on Windows, Mac, and Linux.

 

Usually, .NET Core tries to search views in the following folders  by using the following names( {1} is the Controller name, {0} is the Action method name):

~/Views/{1}/{0}.cshtml
~/Views/Shared/{0}.cshtml

 

This article shows how to customize views paths and names by extending RazorViewEngine and  IViewLocationExpander.

Customize views name

You may need to rewrite the name of searched view , For example:

~/Views/{1}/{0}.vary1.cshtml
~/Views/Shared/{0}.vary2.cshtml

 

UML solution

To customize views name is necessary to extend¬†the¬†RazorViewEngine¬†class, I’ve called the subclass¬†CustomViewEngine:

CustomViewEngine

Code solution

Here is the implementation of CustomViewEngine.cs class:

Important: the Concat method @ line 41 is used to maintain the original locations.

You also need to add the CustomViewEngine class to your Startup.cs file:

Customize view paths

.NET also allows to customize the paths of views, for example :

~/CustomViews/{1}/{0}.cshtml
~/CustomViews/Shared/{0}.cshtml

 

UML solution

To override views path is necessary to extend the IViewLocationExpander class, the subclass name is  CustomViewLocator :

CustomViewLocator

Code solution

Here is the implementation of CustomViewLocator.cs class:

You also need to add the CustomViewLocator class to your Startup.cs file:

Conclusion

.NET Core 1.0 offers a lot ways to customize itself by using OOP fundamentals. As open source framework, Companies and user can rewrite and customize every single part of it.

It is also very easy access to the source code, which is available on Github.

The repo of this article is available here.

Cheers ūüôā

About Samuele Resca

Samuele Resca is an Microsoft MVP Visual Studio and Development Technologies, Software Engineer, specializing mainly on ASP.NET MVC and in general about everything that revolves around the web. Samuele was born in 1994, and works as a software developer @ YOOX NET-A-PORTER Group He loves the MVC frameworks, ASP.NET MVC, Javascript, Node.js and Typescript.