Search code examples
blazorblazor-server-sideblazor-client-side

What are the ways for client side blazor to fetch data from server?


I am experimenting with Blazor client-side for some time now and I notice that majority of different tutorials suggest client side blazor to fetch data via server side web-api.

I am not sure why is that so. Why is it not possible for razor to call a server method instead a developer having to expose same data to API. Why this extra step?

For example

@page "/"
@inject HttpClient Http

<button onclick=@(async () => await PrintWebApiResponse())>Print Web API Response</button>

@functions {
    private async Task PrintWebApiResponse()
    {
        var response = await Http.GetStringAsync("/api/Customer");
        Console.WriteLine(response);
    }
}

Could this be rewriten to be

@page "/"
@inject HttpClient Http

<button onclick=@(async () => await PrintWebApiResponse())>Print Web API Response</button>

@functions {
    private async Task PrintWebApiResponse()
    {

        ServerServices.Service service = new ServerServices.Service();
        var response = service.GetCustomer();

        Console.WriteLine(response);
    }
}

I just tried it (code was part of a partial class in Page Model) and it works perfectly fine. Am i missing a point here? Why is it recommended to expose this method over API?


Solution

  • I'm not sure how you've got your test code setup but it's physically not possible to do what you're implying. Blazor WebAssembly runs entirely on the client, the whole app is bootstrapped and run there. It has no active connection to the server to be able to access a server-side service. This is why you need to make calls to the server using Web APIs.

    Blazor WebAssembly is still a client-side single-page application framework, like Angular or Vue, it just happens to use C#.