3

我正在尝试从不同的程序集加载 ViewComponent 但在主项目中我收到以下错误

InvalidOperationException:找不到名为“Pro.ItemViewComponent”的视图组件。视图组件必须是公共的非抽象类,不包含任何通用参数,并且要么用“ViewComponentAttribute”装饰,要么具有以“ViewComponent”后缀结尾的类名。视图组件不能用“NonViewComponentAttribute”装饰。

库.csproj

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<None 
Remove="Views\Shared\Components\ContainerViewComponent\Default.cshtml"/>
<None Remove="Views\Shared\Components\ItemViewComponent\Default.cshtml" />
<None Remove="Views\Shared\_ViewImports.cshtml" />
</ItemGroup>

<ItemGroup>
<Content 
Include="Views\Shared\Components\ContainerViewComponent\Default.cshtml">
  <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  <Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
<Content Include="Views\Shared\Components\ItemViewComponent\Default.cshtml">
  <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  <Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
<Content Include="Views\Shared\_ViewImports.cshtml">
  <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  <Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
</ItemGroup>
<ItemGroup>
    <EmbeddedResource Include="Views/**/*.cshtml" />
</ItemGroup>
<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.1" />
</ItemGroup>

主项目中的 Startup.cs。

var assembly = typeof(Pro.ItemViewComponent).Assembly;
var embeddedFileProvider = new EmbeddedFileProvider(
    assembly,
    "Pro"
);

services.Configure<RazorViewEngineOptions>(options =>
{
    options.FileProviders.Add(embeddedFileProvider);
});

我在 StackOverflow 中关注了许多文章和一些问题和答案,但我没有找到任何解决方案,我应该怎么做才能从不同的程序集中共享 ViewComponent?

4

1 回答 1

4

问题在 Startup.cs 中的配置非常简单,我必须在services.AddMvc().AddApplicationPart(myAssembly);下面添加完整配置。

var myAssembly = typeof(MyViewComponent).Assembly;

services.AddMvc().AddApplicationPart(myAssembly);

services.Configure<RazorViewEngineOptions>(options =>
 {
       options.FileProviders.Add(new EmbeddedFileProvider(myAssembly, "ComponentLib"));          
 });
于 2018-09-12T20:10:29.793 回答