mko*_*mko 2 blazor blazor-server-side blazor-client-side
我现在正在尝试 Blazor 客户端一段时间,我注意到大多数不同的教程都建议客户端 blazor 通过服务器端 web-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);
}
}
Run Code Online (Sandbox Code Playgroud)
这可以改写为
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
我刚刚尝试过(代码是页面模型中部分类的一部分)并且它工作得非常好。我在这里遗漏了一点吗?为什么建议通过 API 公开此方法?
我不确定你是如何设置测试代码的,但实际上不可能按照你的意思去做。Blazor WebAssembly 完全在客户端上运行,整个应用程序都在那里引导并运行。它没有与服务器的活动连接,无法访问服务器端服务。这就是为什么您需要使用 Web API 调用服务器的原因。
Blazor WebAssembly 仍然是一个客户端单页应用程序框架,就像 Angular 或 Vue 一样,只是碰巧使用了 C#。
归档时间: |
|
查看次数: |
1937 次 |
最近记录: |