Detect client or server mode

I am building a Blazor application which can switch between client mode and server mode. Parts of the application work only in one or the other and need to have fallback code executed in that case.

Is there a good way to check for example if Mono is running or not?

Any suggestions?

Upvotes: 5

Views: 1708

Answers (5)

Nicholas Blumhardt
Nicholas Blumhardt

Reputation: 31842

It's now:

RuntimeInformation.ProcessArchitecture == Architecture.Wasm

Upvotes: 5

Major
Major

Reputation: 6688

This answer was provided by Microsoft here.

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

Upvotes: 1

Simon
Simon

Reputation: 34880

using RuntimeInformation.OSDescription

RuntimeInformation.OSDescription == "web"

Upvotes: 4

Steven T. Cramer
Steven T. Cramer

Reputation: 1518

Using the JSRuntime.Current is not reliable given it is null during startup. The following should work at anytime.

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

I add this class to the DI Container and thus can drive behavior with it.

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

Upvotes: 1

enet
enet

Reputation: 45684

Perhaps this can help you:

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

See also the instructions about BlazorDualMode which allows you to run your app in both modes as well as checking which mode is running.

Hope this helps.

Upvotes: 2

Related Questions