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

2

16

Context:

We want to create a Single Page Application that runs with Blazor WebAssembly on the client-side. On the server-side, the solution has an ASP.NET MVC which includes some ApiController classes for our REST APIs.

We want to use ASP.NET API on the server-side instead of Blazor Server because we want to provide a REST interface with ApiController classes for unknown consumers.

Here is my client-side (Blazor WebAssembly) and server-side (ASP.NET API) project in a single solution:

enter image description here

enter image description here

A first try to request the API via Blazor´s HttpClient-class in our FetchData-component:

@inject HttpClient Http
...
@code {
    private TodoItem[] TodoItems;

    protected override async Task OnInitializedAsync()
    {
        TodoItems = await Http.GetJsonAsync<TodoItem[]>("api/ToDo");
    }
}

On server-side the API-Controller looks like:

namespace ToDoListAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    public class ToDoController : ControllerBase
    {
        [HttpGet]
        public string IGetAll() 
        {
            var lResult = new List<ToDoList.TodoItem>();

            // create dummies
            for (var i = 0; i < 10; i++)
            {
                lResult.Add(new ToDoList.TodoItem() { Title = $"Title {i}", IsDone = false });
            }

            return JsonSerializer.Serialize(lResult);
        }
    }
}

Problem: In my Blazor WebAssembly Project the request to the API fails. The Blazor WebAssembly Project is hosted via https://localhost:44340/ and the API is hosted via https://localhost:44349/. How can I host both projects together as I would it do with a JavaScript Framework?

Dobb answered 3/4, 2020 at 12:24 Comment(0)
W
29

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

Weltanschauung answered 3/4, 2020 at 12:44 Comment(8)
Why do you suggest an Blazor-Server when I want to have an RESTful Server API with ASP.NET Core API?Dobb
it's not a blazor server, it's the server for your Blazor wasm application.Weltanschauung
Exactly what I do in MyStartup for theidserver.herokuapp.comWeltanschauung
When I execute your suggested cmd 'dotnet new bazorwasm --hosted' then I get the following error 'No templates matched the input template name: bazorwasm'.Dobb
install the SDK 3.1.300, that should include blazorwasm template learn.microsoft.com/en-us/aspnet/core/blazor/…Weltanschauung
The "All in one host" was exactly what I was looking for. Thank you!Drandell
Thanks, this is what I was looking for.Angeliaangelic
All in one host (or hosted Blazor webassembly as it is called by Microsoft) can be created by selecting the hosted checkbox when creating the project (MS doc). This sets up a Blazor webassembly, Api and shared class library project, hosted from one location. Perfect.Cenobite
P
11

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/

Palter answered 30/4, 2020 at 9:7 Comment(1)
Did this change with .NET 8?Grosgrain

© 2022 - 2024 — McMap. All rights reserved.