Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 687
Simon Avatar asked Apr 03 '20 12:04

Simon


2 Answers

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

like image 156
agua from mars Avatar answered Sep 23 '22 13:09

agua from mars


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/

like image 45
Neil Thompson Avatar answered Sep 24 '22 13:09

Neil Thompson