我如何使MVC在最后的视图/共享文件夹中寻找razor和webforms视图

本文关键字:视图 文件夹 寻找 razor webforms 共享文件 何使 MVC 最后的 共享 | 更新日期: 2023-09-27 18:08:37

我有一个较旧的ASP。NET MVC应用程序,使用经典的web表单视图。作为一个实验,我们已经开始混合一些剃刀的观点。不幸的是,查找所需视图的默认优先级不是我想要的。MVC首先在/Views/ControllerName文件夹中查找aspx和ascx文件。然后它移动到/Views/Shared(用于aspx和ascx文件)。然后重新开始查找.cshtml和.vbhtml文件。我想要的是它不进入共享文件夹,直到它用尽所有的可能性在/Views/ControllerName文件夹。我该怎么做呢?

——

这里有一些额外的信息可能有助于解释我所追求的。默认情况下,我得到这样的搜索顺序:

~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml 

我想要的是这个:

~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

换句话说,它不应该在完全搜索/Views/ControllerName文件夹之前搜索Shared

我如何使MVC在最后的视图/共享文件夹中寻找razor和webforms视图

你可以在global.asax.cs文件中配置视图引擎的优先级

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new RazorViewEngine());
        ViewEngines.Engines.Add(new WebFormViewEngine());
    }

在摆弄了一下之后,我能够用一个简单的Fluent API实现我想要的。扩展方法从每个视图引擎中删除了我不想要的搜索位置。搜索位置存储在.ViewLocationFormats.PartialViewLocationFormats字符串数组中。下面是从这些数组中删除不需要的项的流畅API:

public static class BuildManagerViewEngineFluentExtensions {
    public static BuildManagerViewEngine ControllerViews(this BuildManagerViewEngine engine) {
        return FilterViewLocations(engine, x => x.Contains("/Views/Shared/") == false);
    }
    public static BuildManagerViewEngine SharedViews(this BuildManagerViewEngine engine) {
        return FilterViewLocations(engine, x => x.Contains("/Views/Shared/") == true);
    }
    private static BuildManagerViewEngine FilterViewLocations(BuildManagerViewEngine engine, Func<string, bool> whereClause) {
        engine.ViewLocationFormats = engine.ViewLocationFormats.Where(whereClause).ToArray();
        engine.PartialViewLocationFormats = engine.PartialViewLocationFormats.Where(whereClause).ToArray();
        return engine;
    }
}

然后,在我的全局。然后,我在protected void Application_Start()

中添加了以下行
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine().ControllerViews());
ViewEngines.Engines.Add(new WebFormViewEngine().ControllerViews());
ViewEngines.Engines.Add(new RazorViewEngine().SharedViews());
ViewEngines.Engines.Add(new WebFormViewEngine().SharedViews());