I am doing a research on Asp.net blazor, and I have found an article on Blazor hosting.
https://docs.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-3.0
I am interested to find out how difficult would be to switch from server-side Blazor hosting model to client-side and other way arround?
It's not difficult at all. Robin Sue has already got this working and I would suggest checking out his Blazor Dual mode repo. Here are his instructions for adding dual mode.
Create a Blazor (ASP.NET Core hosted) Project, then change the Startup class of the .Server Project to enable server side features. This doesn't have adverse effects on Client Side Blazor but enables the Server Side services. For that you need to have services.AddServerSideBlazor();
in ConfigureServices and endpoints.MapBlazorHub<Client.App>("app")
; in Configure
We can now serve Client Side and Server Side apps but we need to polyfil the HttpClient that is provided in DI in Client Side by default. Server Side doesn't register it by default so we detect this and then register an HttpClient in DI that behaves similiar for compatibility
// Server Side Blazor doesn't register HttpClient by default
if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
{
// Setup HttpClient for server side in a client side compatible fashion
services.AddScoped<HttpClient>(s =>
{
// Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
var uriHelper = s.GetRequiredService<IUriHelper>();
return new HttpClient
{
BaseAddress = new Uri(uriHelper.GetBaseUri())
};
});
}
At this point, the only difference is which blazor JS file we load in the browser. This can be either achieved by serving a different index.html (for which i couldn't see an easy way) or using a small piece of JS to decide which file to load
<script id="blazorMode"></script>
<script>
document.getElementById("blazorMode").src = window.location.search.includes("mode=server") ? "_framework/blazor.server.js" : "_framework/blazor.webassembly.js";
</script>
Once again this is all work by Robin Sue and full credit goes to him.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With