asp.net 在Blazor中设置为自动时确定当前渲染模式

ni65a41a  于 5个月前  发布在  .NET
关注(0)|答案(2)|浏览(94)

我正在处理一个Blazor项目,其中组件的渲染模式设置为Auto。根据Blazor文档,这意味着组件最初使用Blazor Server托管模型在服务器端进行交互渲染。.NET运行时和应用程序包在后台下载到客户端并缓存以供将来访问时使用。
这里是我的问题的一点上下文:我有一个内部服务器API,它不能在服务器外部访问,也不能从客户端的浏览器调用。我想在Auto模式组件中调用该API。If it's running on Server mode, the call will be successful as it will work. But if it's in WebAssembly mode, the HTTP request will be sent from the client和客户端无法访问该URL:

@page "/http"
@inject HttpClient Http
@rendermode InteractiveAuto

<h3>HTTP Response</h3>

<p>@_response</p>

@code {
    private string _response = string.Empty;

    protected override async Task OnInitializedAsync ()
    {
        var response = await Http.GetAsync ("http://api.internalhost");
        _response = await response.Content.ReadAsStringAsync ();
    }
}

字符串
所以我的问题是当渲染模式设置为Auto时,如何在运行时确定组件是以WebAssembly模式还是以服务器模式渲染?
在此先谢谢您!

ubby3x7f

ubby3x7f1#

有一个非常简单的解决方案来实现这一点。在C#中,我们在System中有一个名为OperatingSystem的类,它有一个方法来检查代码是否在浏览器上运行(当然使用WASM)。
在.NET 8中,如果Blazor组件是交互式渲染的,那么它要么由服务器使用WebSocket处理,要么由客户端使用WebAssembly处理。因此,如果代码不是使用WASM运行的,那么它是在服务器模式下运行的。下面是一个示例:

@rendermode InteractiveAuto
@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, @handler!</h1>

@code
{
    string handler;

    protected override void OnInitialized ()
    {
        if (OperatingSystem.IsBrowser())
        {
            handler = "WASM";
        }
        else
        {
            handler = "Server";
        }
    }
}

字符串

kcwpcxri

kcwpcxri2#

我不确定你行不行。
你需要重新考虑你的设计。
从UI进行的数据调用应该通过定义为接口IDataBroker的某种数据代理进行。然后定义一个ServerDataBroker,在服务器模式下将其加载为IDataBroker服务,在WASM中将其加载为IDataBroker服务。
组件不需要知道实现,DI为上下文提供了正确的服务。

相关问题