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!
2
Answers
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:
I’m not sure that you can.
You need to rethink your design.
Your data calls from the UI should be made through a data broker of some sort defined as an interface
IDataBroker
. You then define aServerDataBroker
which you load as theIDataBroker
service in server mode andWASMDataBroker
which you load as theIDataBroker
service in WASM.The component doesn’t need to know about the implementation. DI provides the right service for the context.