Search code examples
c#asp.netblazor

Determining the Current Render Mode in Blazor When Set to Auto at Runtime


I'm working with a Blazor project where the render mode of my components is set to Auto. According to the Blazor documentation, this means that the component is initially rendered server-side with interactivity using the Blazor Server hosting model. The .NET runtime and app bundle are downloaded to the client in the background and cached for use on future visits.

Here's a bit of context to my question: I have an internal server API that is not accessible outside the server and can't be called from clients' browsers. I want to call that API inside an Auto mode component. 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 and clients cannot access that 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 ();
    }
}

So, my question is: How can I determine at runtime whether the component is being rendered in WebAssembly or Server mode when the render mode is set to Auto?

Thank you in advance!


Solution

  • There's a very simple solution to achieve this. In C#, we have a class inside System named OperatingSystem that has a method to check if the code is running on the browser (using WASM of course) or not.

    In .NET 8, if a Blazor component is being rendered interactively, then it's either being handled by the server using WebSocket, or by client using WebAssembly. So if the code is not running using WASM, then it's running in Server mode. Here's an example:

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