Blazor Server and Hot Reload Challenges
By: Shaun Walker
So I recently created a simple report generator. The reports are generated in HTML format on the server based on inputs from a user. This was very simple to create in Oqtane using the Module Creator to scaffold the initial module and then make customizations to the code. Basically the module has a user interface on the client to collect parameters from the end user and an API method on the server to generate the report. This took less than an hour to create, however I ran into some unexpected behavior during the testing which caused some challenges.
The unexpected behavior was that after clicking the button to generate the report, the report would be successfully created on the server, however the Blazor UI component would refresh and lose its state resulting in a broken user experience. Investigating further, it appeared that the SignalR web socket connection was being disconnected (as this was running on Blazor Server). But what was causing the web socket circuit to be broken?
There was nothing in the code which could cause this type of behavior - all potential exception conditions were being handled and no exceptions were being thrown. The next possibility was a possible timeout scenario, however the report generation was not a long running process so it did not seem to be root cause. Focusing on the events which can cause web sockets to be broken, I happened to come across a Stack Overflow reference to Hot Reload.
Hot Reload was introduced in .NET 6 and it is enabled by default in the latest versions of Visual Studio. The idea behind Hot Reload is that developers can modify code assets in their project and those changes will be immediately reflected in their run-time development environment. This was a key aspect of improving the "inner productivity loop" for developers in .NET 6.
Sure enough, after further investigation it turns out that when my report generator dynamically creates an HTML document on the server, Hot Reload is causing a reload of the browser page which is causing the web socket to be disconnected. So it is causing my Blazor application to lose state, resulting in a broken user experience.
Luckily, Hot Reload is only active in development environments - not production environments. And it is possible to disable the functionality from within Visual Studio in the Tools / Options / Projects and Solutions / ASP.NET Core option. You can change the "Auto build and refresh option" to None. Obviously, you should only disable this option if you are not actively utilizing Hot Reload for development (I do not find it to be useful for my preferred development style so this solution solved my problem).