How can I host ASP.NET API and Blazor Web Assembly like an JavaScript-SPA?

You can either, depending on how you want to host and deploy your solution :

API and application in 2 different hosts

Enable CORS in the API project Startup class :

public void Configure(IApplicationBuilder app)
{
    ...
    app.UseCors(configure => 
    {
         // configure here your CORS rule
    }
    ...
}

All in one host

In your API project

  • add a package reference to Microsoft.AspNetCore.Components.WebAssembly.Server
  • Setup the blazor server in your Startup class
public void Configure(IApplicationBuilder app)
{
    app.UseBlazorFrameworkFiles();
    ...
    app.UseEndpoints(endpoints => 
   {
       endpoints.MapDefaultControllerRoute();
       endpoints.MapFallbackToFile("index.html");
   });
}

You can create a sample solution with : dotnet new blazorwasm --hosted. It'll create a solution with a Blazor wasm project and a host.

Docs


With the latest update to the templates dotnet new -i Microsoft.AspNetCore.Components.WebAssembly.Templates::3.2.0-preview2.20160.5

You can create a Blazor WebAssembly app setup with authentication using ASP.NET Core Identity and IdentityServer by running the following command:

dotnet new blazorwasm --hosted --auth Individual -o BlazorAppWithAuth1

This creates:

  • Client Side Blazor

  • A single Project that can be used for MVC, API and razor pages, that contains an "inline" IdentityServer which can be used to secure the API calls

I was stuck on how to have IS4 in the same project as the APi (it's a small project and a independently hosted IDP would be overkill and I just want to deploy one thing) but this template shows how.

source: https://devblogs.microsoft.com/aspnet/blazor-webassembly-3-2-0-preview-2-release-now-available/