Inject framework HttpClient to support prerendering behavior on server instead of baking in the HttpClient on the client project

This commit is contained in:
daniel-c-harvey
2025-09-04 09:48:58 -04:00
parent 9124e82e24
commit d556d32829
9 changed files with 59 additions and 33 deletions
-5
View File
@@ -24,9 +24,4 @@
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="9.*" />
</ItemGroup>
<ItemGroup>
<Folder Include="Components\Pages\Auth\" />
</ItemGroup>
</Project>
+6 -4
View File
@@ -1,18 +1,20 @@
using DeepDrftWeb;
using MudBlazor.Services;
using DeepDrftWeb.Components;
using DeepDrftWeb.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add MudBlazor services
builder.Services.AddMudServices();
// Add HttpClient services for prerendering
builder.Services.AddHttpClient("DeepDrft.API", client => client.BaseAddress = new Uri(Startup.GetKestrelUrl(builder)));
builder.Services.AddScoped(sp =>
sp.GetRequiredService<IHttpClientFactory>().CreateClient("DeepDrft.API"));
Startup.ConfigureDomainServices(builder);
var hostUrl = builder.Configuration.GetValue<string>("ASPNETCORE_URLS")?.Split(';').First() ?? throw new Exception("ASPNETCORE_URLS undefined");
DeepDrftWeb.Client.Startup.ConfigureDomainServices(builder.Services, hostUrl);
DeepDrftWeb.Client.Startup.ConfigureDomainServices(builder.Services);
builder.Services.AddControllers();
+26
View File
@@ -16,6 +16,32 @@ public static class Startup
// Add Track services
builder.Services.AddScoped<TrackRepository>();
builder.Services.AddScoped<TrackService>();
}
public static string GetKestrelUrl(this WebApplicationBuilder builder)
{
// Check all the places Kestrel URL can be configured
var urls = builder.Configuration["ASPNETCORE_URLS"]
?? builder.Configuration["urls"];
if (!string.IsNullOrEmpty(urls))
{
return urls.Split(';')[0].Trim();
}
// Check Kestrel endpoints configuration
var kestrelSection = builder.Configuration.GetSection("Kestrel:Endpoints");
var firstEndpoint = kestrelSection.GetChildren().FirstOrDefault();
var endpointUrl = firstEndpoint?["Url"];
if (!string.IsNullOrEmpty(endpointUrl))
{
return endpointUrl;
}
// ASP.NET Core defaults
return builder.Environment.IsDevelopment()
? "https://localhost:5001"
: "http://localhost:5000";
}
}
+2 -1
View File
@@ -4,5 +4,6 @@
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
},
"DetailedErrors": true
}