Custom View Engine in ASP.NET 5

Posted by Anuraj on Friday, August 28, 2015 Reading time :1 minute

.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
            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 =>{

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

Happy Programming :)

What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.

Similar Posts

Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon

BMC logoBuy me a coffee

Copyright © 2019 - 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