Asp.net core 3.1 找不到要渲染的 Razor 组件

Chr*_*ian 5 .net asp.net-core blazor razor-components

我正在尝试将 Blazor 集成到现有的 asp.net core 3.1 应用程序中。我看过的所有教程都说,在 web 项目中进行正确设置后,您应该能够在任何 cshtml 文件中执行此操作:

<component>
    @(await Html.RenderComponentAsync<HelloComponent>(RenderMode.ServerPrerendered))
</component>
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个: 在此处输入图片说明

找不到类型或命名空间“HelloComponent”。

我做了什么

1) 在我的 Startup.cs 中添加了以下内容

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    // .. removed other services...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseRouting();            
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapControllers();
        endpoints.MapRazorPages();
        endpoints.MapBlazorHub();
    });
    // .. removed the rest of configuration..
}
Run Code Online (Sandbox Code Playgroud)

2) 将 _Imports.razor 文件添加到 /Pages 文件夹

@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop    
@using WebApp.Pages.Shared.Components // The location of my HelloComponent
Run Code Online (Sandbox Code Playgroud)

3) 添加了仅包含一些文本的新 Razor 组件。

在此处输入图片说明

4) 添加到_Layout.cshtml

<base href="~/" /> // In header
<script src="_framework/blazor.server.js"></script> // In bottom script section
Run Code Online (Sandbox Code Playgroud)

Rya*_*yan 6

您还需要添加对Components文件夹的引用Pages/_ViewImports.cshtml

@using WebApp

@using WebApp.Pages.Shared.Components

@namespace WebApp.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Run Code Online (Sandbox Code Playgroud)