检测客户端或服务器模式

Detect client or server mode

我正在构建一个可以在客户端模式和服务器模式之间切换的 Blazor 应用程序。应用程序的某些部分只能在其中一种情况下工作,并且需要在这种情况下执行回退代码。

是否有好的方法来检查 Mono 是否 运行 等?

有什么建议吗?

也许这可以帮到你:

// Mono WebAssembly is running.
if (JSRuntime.Current is MonoWebAssemblyJSRuntime mono)
{
}
else
{
}

另请参阅 instructions about BlazorDualMode,它允许您在两种模式下 运行 您的应用程序,并检查哪种模式是 运行ning。

希望对您有所帮助。

使用 JSRuntime.Current 是不可靠的,因为它在启动期间为空。以下内容应该随时可用。

Type.GetType("Mono.Runtime") != null;

我将这个 class 添加到 DI 容器中,因此可以用它驱动行为。

  public class JsRuntimeLocation
  {
    public bool IsClientSide => HasMono;
    public bool IsServerSide => !HasMono;
    public bool HasMono => Type.GetType("Mono.Runtime") != null;
  }

使用RuntimeInformation.OSDescription

RuntimeInformation.OSDescription == "web"

此答案由 Microsoft here 提供。

RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY"))