asp.net.netasp.net-corepartial-viewsviewengine

Custom View Engine not finding a view


I've successfully created a custom view engine and able to browse custom views that are found in different location other than the default. eg/Views/Module1/Controller/ViewName Since my custom view engine overrides the default view route, it is unable to open views that are found in default location. (/View/Controller/ViewName). At this time I modified my custom view engine to refer the default location also. But I ended up getting this kind of error

System.InvalidOperationException: 'The view 'Login' was not found. The following locations were searched:
/Account/Login.cshtml
/Shared/Login.cshtml'
/Module1/Account/Login

Login.cshtml is really found in /Account/Login.cshtml but it is not getting it even if it says that it searched on that directory. my custom view engine looks like this

    public class LibraryViewEngine : IViewLocationExpander
    {
        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            yield return "/{1}/{0}.cshtml";
            yield return "/Module1/{1}/{0}.cshtml";
            yield return "/Module1/Shared/{0}.cshtml";
            yield return "/Shared/{0}.cshtml";
        }

        public void PopulateValues(ViewLocationExpanderContext context)
        {
        }
    }

and added the reference on startup

  services.Configure<RazorViewEngineOptions>(o =>
            {
                o.ViewLocationExpanders.Add(new LibraryViewEngine());
            });

My problem is the same with this question but we're using different version and we're using different way of implementing custom view engine. My .net versin is ASP.NET CORE (5.0) and I am using IViewLocationExpander to implement custom view engine.


Solution

  • Could you pld try codes below?

    yield return "Views/{1}/{0}.cshtml";
    yield return "Views/Shared/{0}.cshtml";
    

    I also did a test in my side with your code, and I faced the same error. So I tried to change my controller to return View("Views/Hello/Index.cshtml") instead of the default return View(), then I found the issue became can't find _layout.cshtml, so I'm afraid the issue should relate to ExpandViewLocations. And after adding Views before the route string, my code worked again.