[英]ASP.NET Core and View conflict resolution
我正在嘗試為 ASP.NET Core 應用程序構建一個插件系統。 我在應用程序中有一個名為“插件”的文件夾。
一般來說,一個插件看起來像一個包含兩個文件的文件夾:Plugin.dll 和 Plugin.Views.dll 應用程序掃描這個文件夾並加載這些程序集
foreach (var ext in extensionManager.Extensions)
{
mvcBuilder.AddApplicationPart(ext.Assembly);
if (ext.ViewsAssembly != null)
{
mvcBuilder.AddApplicationPart(ext.ViewsAssembly);
}
}
如果這些插件具有同名的 ViewComponents,我會收到錯誤消息。 Plugin1 中的模型可以傳遞到 Plugin2 的 Razor 視圖中。
The model item passed into the ViewDataDictionary is of type 'Plugin1.Models.MyModel',
but this ViewDataDictionary instance requires a model item of type 'Plugin2.Models.MyModel'
我該如何解決這個沖突?
傳遞到 ViewDataDictionary 的模型項的類型為“Plugin1.Models.MyModel”,但此 ViewDataDictionary 實例需要類型為“Plugin2.Models.MyModel”的模型項
如果這個 ViewDataDictionary 實例需要一個Plugin2.Models.MyModel
類型的模型項,你可以嘗試使用全名Plugin2.Models.MyModel
。這樣它就不會將Plugin1.Models.MyModel
傳遞給這個 ViewDataDictionary。
我通過將此Target
添加到我的插件的 .csproj 文件中解決了這個問題:
<Target Name="UpdateTargetPath" BeforeTargets="AssignRazorGenerateTargetPaths">
<ItemGroup>
<RazorGenerate Link="$(TargetName)\%(RazorGenerate.RelativeDir)%(RazorGenerate.FileName)%(RazorGenerate.Extension)" />
</ItemGroup>
</Target>
我以這個答案為基礎。 我還從RazorGenerate
標記中刪除了Include
屬性,因為它在生成的程序RazorCompiledAttribute
復制了RazorCompiledAttribute
。
在主機應用程序方面,我擴展了視圖位置格式:
services.Configure<RazorViewEngineOptions>(opts =>
{
var pluginName = ext.Assembly.GetName().Name;
opts.ViewLocationFormats.Add($"/{pluginName}/Views/Shared/{{0}}.cshtml");
opts.ViewLocationFormats.Add($"/{pluginName}/{{1}}/Views/{{0}}.cshtml");
});
在插件中,我必須指定視圖的完全限定路徑:
return View($"/{this.GetType().Assembly.GetName().Name}/Views/Path/To/MyView.cshtml", model);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.