Custom View Engine in ASP.NET 5

Posted by Anuraj on Friday, August 28, 2015

.Net ASP.Net ASP.Net MVC

This post is about implementing Custom View Engine in ASP.NET 5. Normally ASP.NET MVC looks for view files (*.cshtml), inside Views/Controller folder. If you want to configure it to some other location, you can manage it via custom view engine. Here is the implementation.

public class CustomUIViewEngine : RazorViewEngine
{
    public CustomUIViewEngine(IRazorPageFactory pageFactory,
       IRazorViewFactory viewFactory,
       IOptions<RazorViewEngineOptions> optionsAccessor,
       IViewLocationCache viewLocationCache) :
       base(pageFactory, viewFactory, optionsAccessor, viewLocationCache)
    {
    }
    public override IEnumerable<string> ViewLocationFormats
    {
        get
        {
            var viewLocationFormats = base.ViewLocationFormats
            .Union(new string[]{ "~/Views/{1}/UI/{0}.cshtml" });
            return viewLocationFormats;
        }
    }
}

This implementation is different than custom view engine implementation in previous versions of ASP.NET MVC. In ASP.NET MVC 5 or previous, ViewLocationFormats added in the constructor, but it is not possible, since ViewLocationFormats property is readonly.

Here is the modified folder structure include UI folder.

Modified folder structure with UI folder

You can configure this view engine in the Startup.cs, ConfigureServices() method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().Configure<MvcViewOptions>(options =>{
        options.ViewEngines.Clear();
        options.ViewEngines.Add(typeof(CustomUIViewEngine));
    });
}

This code is clearing the existing view engines and adding the new custom view engine.

Happy Programming :)



Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



MVP
Subscribe
Archives


Copyright © 2017 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub