Search code examples
c#.netblazorblazor-webassembly.net-8.0

How to host server side controllers, with a Blazor Web App (WebAssembly), in .NET 8?


Before .NET 8, hosting server side controllers with a Blazor WebAssembly app was easy. You just clicked the "ASP.NET Core Hosted" checkbox in the project template, and an ASP.NET Core project was created for you, that would host the Blazor WebAssembly client.

With the release of .NET 8, a new template has been introduced called "Blazor Web App". But it does not have the "ASP.NET Core Hosted" checkbox

enter image description here

How am i suposed to host server side controllers then? Does "Blazor Web App" introduce a new system for handling client to server communication?

Microsoft documentation says:

We removed the Blazor Server template, and the ASP.NET Core Hosted option has been removed from the Blazor WebAssembly template. Both of these scenarios are represented by options when using the Blazor Web App template.

But i am not sure how this scenario is "represented by options when using the Blazor Web App template"


Solution

  • When you create a "Blazor Web App" with an Interactivity that includes Wasm you already get a Client and a Server project. The Shared (DTO) project is missing but you can easily add it, it's just a class library.

    Add AddControllers() and MapControllers() to the server's Program.cs and then you can start adding the controllers you need.

       ...
    
    builder.Services.AddControllers();
    var app = builder.Build();
    
       ...
    
    app.MapControllers();
    app.Run();