客户端 blazor 从服务器获取数据的方式有哪些?

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

我正在尝试使用 Blazor 客户端一段时间,我注意到大多数不同的教程都建议客户端 blazor 通过服务器端网络获取数据-api.

我不知道为什么会这样。为什么 razor 不可能调用服务器方法,而开发人员必须将相同的数据公开给 API。为什么这个额外的步骤?

例如

@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);
    }
}

可以改写成

@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);
    }
}

我刚刚试过了(代码是页面模型中部分 class 的一部分)并且它工作得很好。我在这里错过了一点吗?为什么建议在 API 上公开此方法?

我不确定你是如何设置测试代码的,但实际上不可能按照你的意思去做。 Blazor WebAssembly 运行 完全在客户端上,整个应用程序是引导的并且 运行 在那里。它与服务器没有活动连接,无法访问服务器端服务。这就是您需要使用 Web API 调用服务器的原因。

Blazor WebAssembly 仍然是一个客户端单页应用程序框架,就像Angular 或Vue 一样,它只是恰好使用了C#。