I continue to explore ASP.NET Core through the lens of DasBlog, I am finding it fascinating to juxtapose how problems were solved in 2004 verses 2017, it provides an enlightening perspective on the maturity of web development frameworks. A feature of DasBlog that I need to emulate for a Web Core UI replacement is the ability to define and select a theme for your blog.

First step was simply storing the current theme name settings, previously the DasBlog devs created a custom made settings file, however, ASP.NET Web Core seems to assume that app settings will be stored in the appsettings.json file, and that of course looks like this:

"DasBlog": {
    "Theme": "DasBlog"
}

The ViewLocationExpanders provides a straightforward way to view and alter the default paths used by the RazorViewEngine, as you are probably aware it checks /Views/Shared as wells as the /View/* folder associated with controller/method. The following class is designed to replace the shared location with the one I have associated with the theme name stored in the app settings file.

public class DasBlogLocationExpander : IViewLocationExpander
{
    private const string _themeLocation = "/Themes/{0}";
    private string _theme;

    public DasBlogLocationExpander(string theme)
    {
        _theme =  string.Format(_themeLocation, theme);
    }

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        return viewLocations.Select(s => s.Replace("/Views/Shared", _theme));
    }

    public void PopulateValues(ViewLocationExpanderContext context)
    {

    }
}

You then call this code in the Startup class in the ConfigureServices and pull in the predefined theme folder name as follows:

services.Configure<RazorViewEngineOptions>(rveo => {
        rveo.ViewLocationExpanders.Add(new DasBlogLocationExpander(Configuration.GetSection("DasBlog")["Theme"]));
});

Nice and simple, and this code should work for both ASP.NET Core and MVC 6.



July 31, 2017 0:09  Comments [0]
Tagged in ASP.NET | ASP.NET Core
Share on Twitter, Facebook and Google+