c# - 找不到不同程序集中的 ASP.NET Core ViewComponents

标签 c# asp.net-core-mvc asp.net-core-viewcomponent assembly-references view-components

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

InvalidOperationException: A view component named 'Pro.ItemViewComponent' could not be found. A view component must be a public non-abstract class, not contain any generic parameters, and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. A view component must not be decorated with '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?

最佳答案

问题在 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"));          
 });

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

相关文章:

c# - Asp.net core中如何在ViewComponent之间共享ViewData

c# - 如何将运行时参数传递给 ViewComponent Invoke 方法

c# - 使用 SharpPcap 和 Packet.Net 发送 LLDP 数据包

c# - Parallel.For 循环的完整 CPU 使用率

c# - 我可以在 .NET Standard 类库中使用动态吗?

asp.net-core - .NET Core MVC 页面更改后不刷新

c# - 如何在新的 ASP.NET Core 中调用 Web API 非默认构造函数

c# - 覆盖默认代码片段

c# - LINQ - 为匿名类型的只读属性赋值

c# - 什么是 Invoke 和 InvokeAsync 方法?