[Solved] In new Blazor fullstack with net 8, how do I call a service from the client project? – Blazor

by
Maya Patel
.net-8.0 blazor

Quick Fix: In Blazor fullstack with .NET 8, you can call a service from the client project by either using API calls or by creating a Server component and accessing it directly.

The Problem:

In a Blazor full-stack application with .NET 8, an InteractiveWebAssembly component needs to access services from the main project. However, the component is created in the client project, which lacks access to these services. Can we still initiate a web API call from the InteractiveWebAssembly component or should we create a web app in the main project for communication?

The Solutions:

Solution 1: Accessing Server Services in the Client Project

With Blazor full stack in .NET 8, the WebAssembly/Client project and the Server/Main project are separate entities. This means that the Client project doesn’t have direct access to the services defined in the Main project.

To access server-side services from the Client project, you can use one of the following approaches:

  1. Use API Calls: Create a Web API controller in the Main project and expose the desired functionality as endpoints. Then, in the Client project, make HTTP requests to these endpoints to access the server-side services. This approach allows for more flexibility and decoupling between the Client and Server projects.

  2. Create Server Components: In .NET 8, you can create Server Components in the Client project. These components run on the server and have direct access to the services defined in the Main project. You can then use these Server Components in the Client project to access server-side functionality. This approach is more tightly coupled but can provide better performance and reduce the need for API calls.

The choice of approach depends on your specific requirements and the level of decoupling you desire between the Client and Server projects.

Here’s a code snippet that demonstrates how to make a HTTP request to a Web API controller from a Blazor Client component:

using System.Net.Http;
using System.Net.Http.Json;

namespace ClientProject.Pages;

public partial class Index
{
    private HttpClient _httpClient;

    protected override async Task OnInitializedAsync()
    {
        _httpClient = new HttpClient();

        // Make an HTTP request to the Web API controller
        var response = await _httpClient.GetAsync("api/WeatherForecast");

        // Deserialize the response into a list of WeatherForecast objects
        var weatherForecast = await response.Content.ReadFromJsonAsync<List<WeatherForecast>>();

        // Use the weatherForecast data in the UI
    }
}

Remember to replace "api/WeatherForecast" with the actual URL of your Web API controller endpoint.

If you choose to use Server Components, you can create a Server Component in the Client project as follows:

using Microsoft.AspNetCore.Components;

namespace ClientProject.Components;

public class ServerCounter : ServerComponentBase
{
    [Parameter] public int Count { get; set; } = 0;

    protected override async Task OnInitializedAsync()
    {
        // Access the CounterService from the Main project
        var counterService = await GetServiceAsync<ICounterService>();

        // Increment the counter
        Count = await counterService.IncrementAsync();
    }
}

Then, in your Blazor Client component, you can use the Server Counter component as follows:

<ServerCounter Count="@count" />

You can then access the Count property of the Server Counter component to display the current count in the UI.

Solution 2: Using a class library for models and interfaces

This solution involves creating a separate class library project for models and interfaces. This allows you to share these definitions between the client and server projects, ensuring consistency and reducing the risk of errors.
Here’s a step-by-step explanation of the process:

  1. Create a Class Library Project:
  • Create a new class library project in your solution.
  1. Define Models and Interfaces:
  • In the class library project, define the models and interfaces that will be shared between the client and server projects. These models represent the data that will be used in your application.
  1. Create a Service Interface:
  • Create an interface in the class library project that defines the methods and properties for the service you want to use in the client project.
  1. Implement the Service Interface in the Server Project:
  • In the server project, create a class that implements the service interface defined in the class library project. This class will contain the logic for accessing the database and performing the necessary operations.
  1. Create a Service Class in the Client Project:
  • In the client project, create a service class that implements the same interface as the one defined in the class library project. This class will be responsible for making API calls to the server-side service.
  1. Configure Dependency Injection:
  • In the client project’s Program.cs file, configure dependency injection to register the service class and the HttpClient service.
  1. Inject the Service in the Client Components:
  • In the client project’s components, inject the service using dependency injection. You can then call the methods of the service to access data from the server.
  1. Create a Web API Controller in the Server Project:
  • In the server project, create a Web API controller that will receive requests from the client project and return the appropriate data.
  1. Communicate with the Database:
  • In the server-side service class, use Dapper or a similar ORM to communicate with the database and retrieve the necessary data.
  1. Expose Data through the Web API Controller:
  • Expose the data retrieved from the database through the Web API controller. The client project will make requests to this controller to fetch the data.
  1. Consume the Web API in the Client Project:
  • In the client project, use the HttpClient service to make API calls to the Web API controller in the server project. This will allow you to retrieve data from the server and display it in the client application.
  1. Maintain a Single Interface:
  • By maintaining a single interface for the service in both the client and server projects, you can easily update the interface in the class library project and have the changes reflected in both projects.
  1. Secure Data Communication:
  • Implementing the service communication through a Web API controller adds an extra layer of security, preventing direct access to the database from the client project.

Q&A

How can I call a service from the client project in Blazor with .net 8?

Use API calls to load data and access server-side services on a WebAssembly/Client component.

Can I create a webapp in the main project and call it from the InteractiveWebAssembly component using http requests?

No, webassembly/Client project is completely separated from the server/Main project and requires its own services.

How can I avoid creating a webapp in the main project and still call a service from the client project?

Create a class library for models and interfaces, implement the interface in both client and server projects, and use an API controller in the server project to communicate with the database.

Video Explanation:

The following video, titled ".NET 7 Blazor WebAssembly Full-Stack Full Course Part 1/2 (with a ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Get the .NET 8 Web Dev Jump-Start Course for FREE: https://dotnet8.patrickgod.com Support me on Patreon for exclusive source code access: ...