【问题标题】:Asp.net core 3.1 can't find Razor component to renderAsp.net core 3.1 找不到要渲染的 Razor 组件
【发布时间】:2020-04-02 16:28:46
【问题描述】:

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

<component>
    @(await Html.RenderComponentAsync<HelloComponent>(RenderMode.ServerPrerendered))
</component>

但是我得到了这个:

找不到类型或命名空间“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..
}

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

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

4) 添加到 _Layout.cshtml

<base href="~/" /> // In header
<script src="_framework/blazor.server.js"></script> // In bottom script section

【问题讨论】:

  • 您是否尝试在您的cshtml页面中添加@using WebApp.Pages.Shared.Components
  • 您在构建项目时在输出中看到了什么?
  • 您是否尝试在 Views/_ViewImports.cshtml 中添加@using WebApp.Pages.Shared.Components

标签: .net asp.net-core blazor razor-components


【解决方案1】:

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

@using WebApp

@using WebApp.Pages.Shared.Components

@namespace WebApp.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

【讨论】:

    【解决方案2】:

    我遇到了这个问题,需要重新启动 Visual Studio...如果胡须很奇怪,请将其关闭并重新打开。

    【讨论】:

    • 当我回答@Ryan 时,VS 认为我在代码部分定义了两次参数,尽管它仍然会构建。为避免这种情况,只需在 1 个地方添加 using 语句,以免破坏智能感知 - 直到他们修复它。此外,解除智能感知错误状态的方法是 - 你猜对了 - 将其关闭,然后再重新打开。
    猜你喜欢
    • 2020-07-19
    • 1970-01-01
    • 2019-08-26
    • 2020-04-10
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多