Luc*_*cas 6 c# razor asp.net-mvc-4 razorgenerator
我有一个大的MVC 4站点,每个MVC区域分成一个项目.我们使用RazorGenerator将我们所有的视图预编译到项目程序集中进行部署,并使用PrecompiledMvcEnginefor我们的ViewEngine.
我刚刚创建了一个新的区域,我希望与Shared另一个程序集共享视图,但是InvalidOperationException在尝试查找部分视图时,我得到了一个,而且找不到任何DisplayTemplates或EditorTemplates.
我认为它类似于这个问题中描述的问题.
我在RazorGenerator App_Start中的代码是这样的:
var assemblies = new List<Tuple<string, Assembly>>()
{
Tuple.Create("Areas/Area1", typeof(ABC.Project1.AreaRegistration).Assembly),
Tuple.Create("Areas/Area2", typeof(ABC.Project2.AreaRegistration).Assembly),
};
// Get rid of the default view engine
ViewEngines.Engines.Clear();
foreach ( var assembly in assemblies )
{
var engine = new PrecompiledMvcEngine(assembly.Item2, assembly.Item1) {
UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
};
// Allow sharing of Area1 Shares views with Area2
if (assembly.Item1 == "Areas/Area2")
{
var sharedPaths = new[] { "~/Areas/Area1/Views/Shared/{0}.cshtml" };
engine.ViewLocationFormats = engine.ViewLocationFormats.Concat(sharedPaths).ToArray();
engine.MasterLocationFormats = engine.MasterLocationFormats.Concat(sharedPaths).ToArray();
engine.PartialViewLocationFormats = engine.PartialViewLocationFormats.Concat(sharedPaths).ToArray();
}
ViewEngines.Engines.Insert(0, engine);
VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
}
Run Code Online (Sandbox Code Playgroud)
当我在Area2中的视图中遇到部分引用时@Html.Partial("Partials/Footer"),我得到了异常.看来Razor正在寻找正确的道路
System.InvalidOperationException: The partial view 'Partials/Footer' was not found or no view engine supports the searched locations. The following locations were searched:
~/Areas/Area2/Views/Home/Partials/Footer.cshtml
~/Areas/Area2/Views/Shared/Partials/Footer.cshtml
~/Views/Home/Partials/Footer.cshtml
~/Views/Shared/Partials/Footer.cshtml
~/Areas/Area1/Views/Shared/Partials/Footer.cshtml
at System.Web.Mvc.HtmlHelper.FindPartialView(ViewContext viewContext, String partialViewName, ViewEngineCollection viewEngineCollection)
Run Code Online (Sandbox Code Playgroud)
查看源代码,PrecompiledMvcEngine看起来它只查找程序集中的视图.
我最初认为视图系统会在尝试解析路径时查看所有已注册的ViewEngine,但这似乎是一个不正确的假设(我可以看到为什么不会这样做).
有没有办法在多个程序集之间共享视图?
更新
我通过创建一个自定义版本来解决这个问题,该版本PrecompiledMvcEngine在其构造函数中获取了一个程序集列表.核心变化是这样的:
_mappings = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
foreach (var kvp in assemblies)
{
var baseVirtualPath = NormalizeBaseVirtualPath(kvp.Key);
var assembly = kvp.Value;
var mapping = from type in assembly.GetTypes()
where typeof(WebPageRenderingBase).IsAssignableFrom(type)
let pageVirtualPath = type.GetCustomAttributes(inherit: false).OfType<PageVirtualPathAttribute>().FirstOrDefault()
where pageVirtualPath != null
select new KeyValuePair<string, Type>(CombineVirtualPaths(baseVirtualPath, pageVirtualPath.VirtualPath), type);
foreach (var map in mapping)
{
_mappings.Add(map);
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法有更好的替代方案或陷阱吗?
| 归档时间: |
|
| 查看次数: |
2123 次 |
| 最近记录: |