在运行时设置为自动时确定 Blazor 中的当前渲染模式

Mat*_*tin 4 c# asp.net blazor

我正在处理 Blazor 项目,其中组件的渲染模式设置为Auto. 根据Blazor 文档,这意味着该组件最初是使用 Blazor 服务器托管模型在服务器端呈现并具有交互性。.NET 运行时和应用程序包在后台下载到客户端并缓存以供将来访问时使用。

以下是我的问题的一些背景信息:我有一个内部服务器 API,无法在服务器外部访问,也无法从客户端浏览器调用。我想在Auto模式组件内调用该 API。如果它在服务器模式下运行,则调用将成功,因为它将起作用。但如果是 WebAssembly 模式,HTTP 请求将从客户端发送,客户端无法访问该 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 ();
    }
}

Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:当渲染模式设置为 时,如何在运行时确定组件是在 WebAssembly 还是服务器模式下渲染Auto

先感谢您!

Mat*_*tin 5

有一个非常简单的解决方案可以实现这一目标。在 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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)