Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Custom View Engine in ASP.NET 5

5.00/5 (1 vote)
19 Sep 2015MIT 8.7K  
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.

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

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 :)

License

This article, along with any associated source code and files, is licensed under The MIT License