客户端服务器从服务器获取数据的方式有哪些? [英] What are the ways for client side blazor to fetch data from server?

查看:95
本文介绍了客户端服务器从服务器获取数据的方式有哪些?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在在Blazor客户端上进行了一段时间的实验,我注意到大多数不同的教程都建议客户端blazor通过服务器端Web-api来获取数据.

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.

我不确定为什么会这样.为什么razor无法调用服务器方法,而开发人员却不得不向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?

例如

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

我刚刚尝试了一下(代码是Page Model中的部分类的一部分),它工作得很好.我在这里遗漏了一点吗?为什么建议通过API公开此方法?

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?

推荐答案

我不确定您如何设置测试代码,但实际上无法执行您所暗示的事情.Blazor WebAssembly完全在客户端上运行,整个应用程序被引导并在那里运行.它没有与服务器的活动连接,因此无法访问服务器端服务.这就是为什么您需要使用Web API调用服务器的原因.

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仍然是客户端单页应用程序框架,例如Angular或Vue,它恰好使用C#.

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

这篇关于客户端服务器从服务器获取数据的方式有哪些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆