Search code examples
c#asp.netrazorowin

ASP.NET How to register Custom View Engine using OWIN


I'm trying to implement Custom View Engine that will let me specify additional View paths that looks like this:

public class CustomViewEngine : RazorViewEngine
{
    public CustomViewEngine()
    {
        ViewLocationFormats = new[]
        {
            "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml",
            "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml"
        };
        MasterLocationFormats = new[]
            {
            "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml",
            "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml"
        };
        PartialViewLocationFormats = new[]
            {
            "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml",
            "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml",
            "~/Views/Partials/Widgets/{0}.cshtml", "~/Views/Partials/Widgets/{0}.vbhtml"
        };

    }
}

There's a lot of source code how to use it in Global.asax.cs for example here: Can I specify a custom location to "search for views" in ASP.NET MVC? but there's no source that would show how to register this Engine when using OWIN. How to do it?


Solution

  • Try this:

    Startup.cs

    using System.Web.Mvc;
    using Microsoft.Owin;
    using Owin;
    
    [assembly: OwinStartup(typeof(WebApplication2.Startup))]
    
    namespace WebApplication2
    {
       public class Startup
       {
          public void Configuration(IAppBuilder app)
          {
             ViewEngines.Engines.Clear();
             ViewEngines.Engines.Add(new CustomViewEngine());
          }
       }
    }