Skip to content

Commit 6e850cb

Browse files
committed
Add Server Side mode switch
1 parent 3cd9471 commit 6e850cb

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

BlazorDualMode.Client/wwwroot/index.html

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<!DOCTYPE html>
1+
<!DOCTYPE html>
22
<html>
33
<head>
44
<meta charset="utf-8" />
@@ -11,6 +11,9 @@
1111
<body>
1212
<app>Loading...</app>
1313

14-
<script src="_framework/blazor.webassembly.js"></script>
14+
<script id="blazorMode"></script>
15+
<script>
16+
document.getElementById("blazorMode").src = window.location.search.includes("mode=server") ? "_framework/blazor.server.js" : "_framework/blazor.webassembly.js";
17+
</script>
1518
</body>
1619
</html>

BlazorDualMode.Server/Startup.cs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
using Microsoft.AspNetCore.Builder;
2+
using Microsoft.AspNetCore.Components;
23
using Microsoft.AspNetCore.Hosting;
34
using Microsoft.AspNetCore.ResponseCompression;
45
using Microsoft.Extensions.DependencyInjection;
56
using Microsoft.Extensions.Hosting;
6-
using Newtonsoft.Json.Serialization;
7+
using System;
78
using System.Linq;
9+
using System.Net.Http;
810

911
namespace BlazorDualMode.Server
1012
{
@@ -15,11 +17,27 @@ public class Startup
1517
public void ConfigureServices(IServiceCollection services)
1618
{
1719
services.AddMvc().AddNewtonsoftJson();
20+
services.AddServerSideBlazor();
1821
services.AddResponseCompression(opts =>
1922
{
2023
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
2124
new[] { "application/octet-stream" });
2225
});
26+
27+
// Server Side Blazor doesn't register HttpClient by default
28+
if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
29+
{
30+
// Setup HttpClient for server side in a client side compatible fashion
31+
services.AddScoped<HttpClient>(s =>
32+
{
33+
// Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
34+
var uriHelper = s.GetRequiredService<IUriHelper>();
35+
return new HttpClient
36+
{
37+
BaseAddress = new Uri(uriHelper.GetBaseUri())
38+
};
39+
});
40+
}
2341
}
2442

2543
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -39,6 +57,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
3957

4058
app.UseEndpoints(endpoints =>
4159
{
60+
endpoints.MapBlazorHub<Client.App>("app");
4261
endpoints.MapDefaultControllerRoute();
4362
endpoints.MapFallbackToClientSideBlazor<Client.Startup>("index.html");
4463
});

0 commit comments

Comments
 (0)