Can't access views from different project using Razor View Engine

折月煮酒 提交于 2021-01-05 07:11:12

问题


I have a use case where I have many web projects that all use the same management general-purpose web pages, so I started to isolate my views to a separate project where all solutions can reference and use.

Because currently, I have to copy-paste the view files across solutions whenever I have a new change.

Based on this answer, I added a new custom view engine, and then added the path to the location where my views live (in a separate project beside my main project).

    public class CustomViewEngine : RazorViewEngine
    {
        public CustomViewEngine()
        {
            MasterLocationFormats = new string[]
            {
        "~/Views/{1}/{0}.aspx",
        "~/Views/{1}/{0}.ascx",
        "~/Views/Shared/{0}.aspx",
        "~/Views/Shared/{0}.ascx",
        "~/Shared.Views/Views/{1}/{0}.aspx",
        "~/Shared.Views/Views/{1}/{0}.ascx",

            };
            ViewLocationFormats = new string[]
            {
        "~/Views/{1}/{0}.aspx",
        "~/Views/{1}/{0}.ascx",
        "~/Views/Shared/{0}.aspx",
        "~/Views/Shared/{0}.ascx",
        "~/../Shared.Views/Views/{1}/{0}.aspx",
        "~/../Shared.Views/Views/{1}/{0}.ascx",
            };
      }
    }

When including the following:

"~/../Shared.Views/Views/{1}/{0}.aspx",
"~/../Shared.Views/Views/{1}/{0}.ascx",

I am getting the following exception:

Cannot use a leading .. to exit above the top directory. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Cannot use a leading .. to exit above the top directory.

My file structure.

Solution
   Shared.Views
      Views
         Profiles
            create.cshtml
            delete.cshtml
            edit.cshtml
            details.cshtml
   MainProject
      Global.asax

What is the correct path I have to add to tell MVC to look for views in my separate project?


回答1:


You can’t reference files in another project like you’re doing. Check out Razor Class Libraries if you’re using ASPNET Core 2.1+



来源:https://stackoverflow.com/questions/65298053/cant-access-views-from-different-project-using-razor-view-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!