gpt4 book ai didi

c# - ASP.NET Core ViewLocationExpander 在其他程序集中找不到 View

转载 作者:太空宇宙 更新时间:2023-11-03 21:00:00 25 4
gpt4 key购买 nike

我有以下解决方案:

src
/Web
/Web.Admin
/Controller
/TestControllr.cs
/Views
/Test
/Index.cshtml

我将应用程序部分用于单独的我的应用程序部分:

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
var adminAssembly = Assembly.Load(new AssemblyName("Web.Admin"));

services.AddMvc().AddApplicationPart(adminAssembly);

services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new AdminViewLocationExpander());

});
}
}

并创建名称为 AdminViewLocationExpander 的 ViewLocationExpander:

public class AdminViewLocationExpander : IViewLocationExpander
{
public void PopulateValues(ViewLocationExpanderContext context)
{
}

public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
const string adminAssembly = "Web.Admin";

var adminViewsLocations = new []
{
$"/{adminAssembly}/Views/{{1}}/{{0}}.cshtml",
$"/{adminAssembly}/Views/Shared/{{0}}.cshtml"
};

viewLocations = adminViewsLocations.Concat(viewLocations);

return viewLocations;
}
}

当我使用此 URL localhost:6046/Test/Index 运行应用程序时,得到以下内容:

 InvalidOperationException: The view 'Index' was not found. The following 
locations were searched:
/Web.Admin/Views/Test/Index.cshtml
/Web.Admin/Views/Shared/Index.cshtml
/Views/Test/Index.cshtml
/Views/Shared/Index.cshtml

我该如何解决这个问题?

最佳答案

在我的项目中,我将 View 作为嵌入资源保存在单独的类库项目/程序集中,打包为 nugets。例如here is one project with embedded views .

我不需要自定义 IViewLocationExpander 来找到它们。相反,我创建了一个这样的扩展方法:

public static RazorViewEngineOptions AddCloudscribeSimpleContentBootstrap3Views(this RazorViewEngineOptions options)
{
options.FileProviders.Add(new EmbeddedFileProvider(
typeof(Bootstrap3).GetTypeInfo().Assembly,
"cloudscribe.SimpleContent.Web.Views.Bootstrap3"
));

return options;
}

然后在主应用程序启动时,我像这样添加它们:

services.AddMvc()
.AddRazorOptions(options =>
{
options.AddCloudscribeSimpleContentBootstrap3Views();


});

在我的带有嵌入式 View 的类库中,我只是像往常一样将它们放在 Views 文件夹中,而在我的 .csproj 文件中,我将它们设为嵌入式资源,如下所示:

<ItemGroup>
<EmbeddedResource Include="Views\**" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>

它们的工作方式就好像它们在磁盘上一样,如果我想覆盖/自定义一个 View ,我可以将它复制到本地,然后将自动使用本地 View 而不是嵌入式 View 。

关于c# - ASP.NET Core ViewLocationExpander 在其他程序集中找不到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46380332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com