View Location Expander in ASP.NET Core and MVC 6

 

        Introduction:

 

                 Yesterday, I wrote about Custom View Engine in ASP.NET Core and MVC 6 with Dynamic View Location, but David Fowler told me that there is another much better and easy way to do this using a new feature in ASP.NET Core and MVC 6 called view location expander. View location expander can be used to determine paths for a view and it is used by RazorViewEngine. This feature makes it very easy to add dynamic view location paths in your application while maintaining the view location cache. In this article, I will show you how to add view location expander feature in your application 

 

        Description:

 

                    Let's create an ASP.NET Core web application (note that I am using beta3 at the time of writing). Here we need to implement IViewLocationExpander interface, 

 

    public class MyViewLocationExpander : IViewLocationExpander
    {
        public void PopulateValues(ViewLocationExpanderContext context)
        {
            var value = new Random().Next(0, 1);
            var theme = value == 0 ? "Theme1" : "Theme2";
            context.Values["theme"] = theme;
        }

        public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
                                                               IEnumerable<string> viewLocations)
        {
            return viewLocations.Select(f => f.Replace("/Views/", "/Views/" + context.Values["theme"] + "/"));
        }
    }

 

                    You can add as many view location expanders as you want. IViewLocationExpander interface has 2 methods, PopulateValues and ExpandViewLocationsPopulateValues method allows you to add values that can be later consumed by ExpandViewLocations method. The values you put in PopulateValues  method will be used to find cache key. ExpandViewLocations method will be only invoked if there is no cache result for the cache key or when framework is unable to find the view at the cached result. In the ExpandViewLocations method, you can return your dynamic view locations. Now you can register this view location expander in Startup.cs file,

 

            services.Configure<RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(typeof(MyViewLocationExpander));
            });

 

                                       

        Summary:

                    View location expander is another cool new feature in ASP.NET Core and MVC 6 which makes it very easy for us to expand our view paths. In this article, I showed you how to use this.

2 Comments

Comments have been disabled for this content.