Asp.net core 3.1 can't find Razor component to render
Asked Answered
M

2

5

Im trying to integrate Blazor into an existing asp.net core 3.1 application. All tutorials I have seen, says that after doing the correct setup in the web project, you should be able to do this in any cshtml file:

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

But instead I get this: enter image description here

The type or namespace 'HelloComponent' could not be found.

What I have done

1) Added following to my 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) Added _Imports.razor file to /Pages folder

@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) Added new Razor Component that contains only some text.

enter image description here

4) Added to _Layout.cshtml

<base href="~/" /> // In header
<script src="_framework/blazor.server.js"></script> // In bottom script section
Maquis answered 9/12, 2019 at 14:35 Comment(3)
Did you try to add the @using WebApp.Pages.Shared.Components in your cshtml page ?Knifeedged
What do you see in your output when you build your project?Shaunta
Did you try to add the @using WebApp.Pages.Shared.Components in Views/_ViewImports.cshtmlKnifeedged
N
6

You also need to add references to Components folder in Pages/_ViewImports.cshtml

@using WebApp

@using WebApp.Pages.Shared.Components

@namespace WebApp.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Nutrient answered 10/12, 2019 at 5:58 Comment(0)
V
1

I had this issue, and needed to reboot Visual Studio... If it's weird with a beard, turn it off and turn it back on.

Valentino answered 5/1, 2021 at 21:2 Comment(1)
When I did @Ryan's answer, VS thought I was defining parameters in the code section twice, though it would still build. To avoid this, just add the using statement in only 1 place to not break intellisense - until if/when they fix it. Also, the way to un-break the intellisense bug state is - you guessed it - turn it off, and then back on again.Valentino

© 2022 - 2024 — McMap. All rights reserved.