Custom View Engine in ASP.NET Core and MVC 6 with Dynamic View Location

 

        Introduction:

 

                 Long time ago, I have written a blog post about how to create a custom view engine in ASP.NET MVC. I thought to write the same for ASP.NET 6 and MVC 6. In this article, I will show you how to create a custom view engine in ASP.NET Core and MVC 6. (Note that ASP.NET Core and MVC 6 is still in beta, so things might change in future)

 

        Description:

 

                    Assuming that you have created an ASP.NET Core web application (note that I am using beta3 at the time of writing). Let's say, you have Theme1 and Theme2 folders inside Views folder and you want to show views from Theme1 or Theme2 folder randomly. Let's implement this by adding MyRazorViewEngine class which inherits from RazorViewEngine class,

 

    public class MyRazorViewEngine : RazorViewEngine
    {
        public MyRazorViewEngine(IRazorPageFactory pageFactory,
            IRazorViewFactory viewFactory,
            IViewLocationExpanderProvider viewLocationExpanderProvider,
            IViewLocationCache viewLocationCache) 
            : base(pageFactory, 
                  viewFactory, 
                  viewLocationExpanderProvider, 
                  viewLocationCache)
        {
        }

        public override IEnumerable<string> AreaViewLocationFormats
        {
            get
            {
                var value = new Random().Next(0, 1);
                var theme = value == 0 ? "Theme1" : "Theme2";
                return base.AreaViewLocationFormats.Select(f => f.Replace("/Views/", "/Views/" + theme + "/"));
            }
        }

        public override IEnumerable<string> ViewLocationFormats
        {
            get
            {
                var value = new Random().Next(0, 1);
                var theme = value == 0 ? "Theme1" : "Theme2";
                return base.ViewLocationFormats.Select(f => f.Replace("/Views/", "/Views/" + theme + "/"));
            }
        }
    }

 

                    Here I am simply overriding AreaViewLocationFormats and ViewLocationFormats properties and appending Theme1 or Theme2(randomly selecting) after Views. Now let's register this view engine in Startup.cs file inside ConfigureServices method,

 

            services.AddMvc().Configure<MvcOptions>(options =>
            {
                options.ViewEngines.Clear();
                options.ViewEngines.Add(typeof(MyRazorViewEngine));
            });

 

                     I am clearing existing view engines and adding our view engine. Now just run this app, you will find that sometimes views are picked from Theme1 folder and sometimes from Theme2 folder.

                   

        Summary:

                    Adding custom view engine is just a piece of cake in ASP.NET Core and MVC 6. In this article, I showed you how to do this.

No Comments