Skip to content

Commit

Permalink
feat(infra): refactor server address usages (#6038) (#6039)
Browse files Browse the repository at this point in the history
  • Loading branch information
ysmoradi authored Nov 14, 2023
1 parent 1260e0e commit 2342898
Show file tree
Hide file tree
Showing 26 changed files with 132 additions and 38 deletions.
7 changes: 7 additions & 0 deletions .github/workflows/adminpanel.cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ jobs:
dotnet pack -c Release -o . -p:ReleaseVersion=0.0.0 -p:PackageVersion=0.0.0
dotnet new install Bit.Boilerplate.0.0.0.nupkg
cd ../../../ && dotnet new bit-bp --name AdminPanel --database SqlServer --sample AdminPanel
- name: Update appsettings.json api server address
uses: microsoft/variable-substitution@v1
with:
files: 'AdminPanel/src/Client/Core/appsettings.json'
env:
ApiServerAddress: ${{ env.API_SERVER_ADDRESS }}

- uses: actions/setup-node@v3
with:
Expand Down
7 changes: 7 additions & 0 deletions .github/workflows/blazorui.demo.cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ jobs:
- uses: actions/setup-node@v3
with:
node-version: 18

- name: Update appsettings.json api server address
uses: microsoft/variable-substitution@v1
with:
files: 'src/BlazorUI/Demo/Client/Core/appsettings.json'
env:
ApiServerAddress: ${{ env.API_SERVER_ADDRESS }}

- name: Switch to blazor web assembly
run: sed -i 's/Microsoft.NET.Sdk.Web/Microsoft.NET.Sdk.BlazorWebAssembly/g' src/BlazorUI/Demo/Client/Web/Bit.BlazorUI.Demo.Client.Web.csproj
Expand Down
7 changes: 7 additions & 0 deletions .github/workflows/todotemplate.cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ jobs:
dotnet new install Bit.Boilerplate.0.0.0.nupkg
cd ../../../ && dotnet new bit-bp --name TodoTemplate --database SqlServer --sample Todo
- name: Update appsettings.json api server address
uses: microsoft/variable-substitution@v1
with:
files: 'TodoTemplate/src/Client/Core/appsettings.json'
env:
ApiServerAddress: ${{ env.API_SERVER_ADDRESS }}

- name: Switch to blazor web assembly
run: sed -i 's/Microsoft.NET.Sdk.Web/Microsoft.NET.Sdk.BlazorWebAssembly/g' TodoTemplate/src/Client/Web/TodoTemplate.Client.Web.csproj

Expand Down
6 changes: 3 additions & 3 deletions src/BlazorUI/Demo/Client/App/MauiProgram.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,10 @@ public static MauiAppBuilder CreateMauiAppBuilder()
#endif

var builder = MauiApp.CreateBuilder();
var assembly = typeof(MainLayout).GetTypeInfo().Assembly;

builder
.UseMauiApp<App>()
.Configuration.AddJsonFile(new EmbeddedFileProvider(assembly), "appsettings.json", optional: false, false);
.Configuration.AddClientConfigurations();

var services = builder.Services;

Expand All @@ -37,11 +36,12 @@ public static MauiAppBuilder CreateMauiAppBuilder()
services.AddBlazorWebViewDeveloperTools();
#endif

Uri.TryCreate(builder.Configuration.GetApiServerAddress(), UriKind.Absolute, out var apiServerAddress);
services.AddScoped(sp =>
{
HttpClient httpClient = new(sp.GetRequiredService<AppHttpClientHandler>())
{
BaseAddress = new Uri(sp.GetRequiredService<IConfiguration>().GetApiServerAddress())
BaseAddress = apiServerAddress
};

return httpClient;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
</PackageReference>
<PackageReference Condition=" '$(BlazorMode)' == 'BlazorWebAssembly' " Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.0-rc.2.23480.2" />
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="8.0.0-rc.2.23480.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0-rc.2.23479.6" />

<Using Include="System.Net.Http.Json" />
<Using Include="System.Collections.Concurrent" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Reflection;

namespace Microsoft.Extensions.Configuration;

public static class IConfigurationBuilderExtensions
{
public static void AddClientConfigurations(this IConfigurationBuilder builder)
{
var assembly = Assembly.Load("Bit.BlazorUI.Demo.Client.Core");
builder.AddJsonStream(assembly.GetManifestResourceStream("Bit.BlazorUI.Demo.Client.Core.appsettings.json")!);
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
namespace Microsoft.Extensions.Configuration;
//-:cnd:noEmit
namespace Microsoft.Extensions.Configuration;
public static class IConfigurationExtensions
{
public static string GetApiServerAddress(this IConfiguration configuration)
{
#if BlazorWebAssembly
return "api/";
#else
return configuration.GetValue<string?>("ApiServerAddress") ?? throw new InvalidOperationException("Could not find ApiServerAddress config");
#endif
var apiServerAddress = configuration.GetValue("ApiServerAddress", defaultValue: "api/")!;

return Uri.TryCreate(apiServerAddress, UriKind.RelativeOrAbsolute, out _) ? apiServerAddress : throw new InvalidOperationException($"Api server address {apiServerAddress} is invalid");
}
}
14 changes: 14 additions & 0 deletions src/BlazorUI/Demo/Client/Web/Extensions/HttpRequestExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ namespace Microsoft.AspNetCore.Http;

public static class HttpRequestExtensions
{
/// <summary>
/// https://blog.elmah.io/how-to-get-base-url-in-asp-net-core/
/// </summary>
public static string GetBaseUrl(this HttpRequest req)
{
var uriBuilder = new UriBuilder(req.Scheme, req.Host.Host, req.Host.Port ?? -1);
if (uriBuilder.Uri.IsDefaultPort)
{
uriBuilder.Port = -1;
}

return uriBuilder.Uri.AbsoluteUri;
}

public static bool ShouldRenderStaticMode(this HttpRequest request)
{
var agent = GetLoweredUserAgent(request);
Expand Down
2 changes: 1 addition & 1 deletion src/BlazorUI/Demo/Client/Web/Program.BlazorElectron.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public partial class Program
public static WebApplication CreateHostBuilder(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonStream(typeof(Core.Shared.MainLayout).Assembly.GetManifestResourceStream("Bit.BlazorUI.Demo.Client.Core.appsettings.json")!);
builder.Configuration.AddClientConfigurations();

builder.WebHost.UseElectron(args);
builder.Services.AddElectron();
Expand Down
2 changes: 1 addition & 1 deletion src/BlazorUI/Demo/Client/Web/Program.BlazorServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public partial class Program
public static WebApplication CreateHostBuilder(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonStream(typeof(Core.Shared.MainLayout).Assembly.GetManifestResourceStream("Bit.BlazorUI.Demo.Client.Core.appsettings.json")!);
builder.Configuration.AddClientConfigurations();

#if DEBUG
if (OperatingSystem.IsWindows())
Expand Down
9 changes: 7 additions & 2 deletions src/BlazorUI/Demo/Client/Web/Program.BlazorWebAssembly.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,16 @@ public partial class Program
public static WebAssemblyHost CreateHostBuilder(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault();
builder.Configuration.AddJsonStream(typeof(Core.Shared.MainLayout).Assembly.GetManifestResourceStream("Bit.BlazorUI.Demo.Client.Core.appsettings.json")!);
builder.Configuration.AddClientConfigurations();

var apiServerAddressConfig = builder.Configuration.GetApiServerAddress();

var apiServerAddress = new Uri($"{builder.HostEnvironment.BaseAddress}{apiServerAddressConfig}");
Uri.TryCreate(builder.Configuration.GetApiServerAddress(), UriKind.RelativeOrAbsolute, out var apiServerAddress);

if (apiServerAddress.IsAbsoluteUri is false)
{
apiServerAddress = new Uri($"{builder.HostEnvironment.BaseAddress}{apiServerAddress}");
}

builder.Services.AddSingleton(sp => new HttpClient(sp.GetRequiredService<AppHttpClientHandler>()) { BaseAddress = apiServerAddress });
builder.Services.AddScoped<Microsoft.AspNetCore.Components.WebAssembly.Services.LazyAssemblyLoader>();
Expand Down
3 changes: 2 additions & 1 deletion src/BlazorUI/Demo/Client/Web/Startup/Services.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ public static class Services
{
public static void Add(IServiceCollection services, IConfiguration configuration)
{
Uri.TryCreate(configuration.GetApiServerAddress(), UriKind.Absolute, out var apiServerAddress);
services.AddScoped(sp =>
{
HttpClient httpClient = new(sp.GetRequiredService<AppHttpClientHandler>())
{
BaseAddress = new Uri(sp.GetRequiredService<IConfiguration>().GetApiServerAddress())
BaseAddress = apiServerAddress
};

return httpClient;
Expand Down
4 changes: 4 additions & 0 deletions src/BlazorUI/Demo/Server/Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
var builder = WebApplication.CreateBuilder(args);

#if BlazorWebAssembly
builder.Configuration.AddClientConfigurations();
#endif

#if DEBUG
if (OperatingSystem.IsWindows())
{
Expand Down
9 changes: 6 additions & 3 deletions src/BlazorUI/Demo/Server/Api/Startup/Services.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,12 @@ public static void Add(IServiceCollection services, IWebHostEnvironment env, ICo
.ConfigurePrimaryHttpMessageHandler<AppHttpClientHandler>()
.ConfigureHttpClient((sp, httpClient) =>
{
NavigationManager navManager = sp.GetRequiredService<IHttpContextAccessor>().HttpContext!.RequestServices.GetRequiredService<NavigationManager>();
httpClient.BaseAddress = new Uri($"{navManager.BaseUri}api/");
Uri.TryCreate(configuration.GetApiServerAddress(), UriKind.RelativeOrAbsolute, out var apiServerAddress);
if (apiServerAddress!.IsAbsoluteUri is false)
{
apiServerAddress = new Uri($"{sp.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.GetBaseUrl()}{apiServerAddress}");
}
httpClient.BaseAddress = apiServerAddress;
});
services.AddScoped<Microsoft.AspNetCore.Components.WebAssembly.Services.LazyAssemblyLoader>();

Expand All @@ -43,7 +47,6 @@ public static void Add(IServiceCollection services, IWebHostEnvironment env, ICo
// for other usages of http client, for example calling 3rd party apis, either use services.AddHttpClient("NamedHttpClient") or services.AddHttpClient<TypedHttpClient>();
});
services.AddRazorPages();
services.AddMvcCore();
#endif

services.AddCors();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,6 @@ jobs:

- name: Install wasm
run: cd src && dotnet workload install wasm-tools wasm-experimental

- name: Update appsettings.json api server address
uses: microsoft/variable-substitution@v1
with:
files: 'src/BlazorWeb.Client/appsettings.json'
env:
ApiServerAddress: ${{ env.API_SERVER_ADDRESS }}

- name: Generate CSS/JS files
run: dotnet build src/BlazorWeb.Client/BlazorWeb.Client.csproj -t:BeforeBuildTasks --no-restore
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ jobs:
- uses: actions/setup-node@v3
with:
node-version: 18

- name: Update appsettings.json api server address
uses: microsoft/variable-substitution@v1
with:
files: 'src/Client/Core/appsettings.json'
env:
ApiServerAddress: ${{ env.API_SERVER_ADDRESS }}

- name: Switch to blazor web assembly
run: sed -i 's/Microsoft.NET.Sdk.Web/Microsoft.NET.Sdk.BlazorWebAssembly/g' src/Client/Web/Boilerplate.Client.Web.csproj
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static MauiApp CreateMauiApp()

builder
.UseMauiApp<App>()
.Configuration.AddJsonFile(new EmbeddedFileProvider(assembly), "appsettings.json", optional: false, false);
.Configuration.AddClientConfigurations();

var services = builder.Services;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public static WebAssemblyHost CreateHostBuilder(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault();

builder.Configuration.AddClientConfigurations();
builder.Configuration.AddClientConfigurations();

Uri.TryCreate(builder.Configuration.GetApiServerAddress(), UriKind.RelativeOrAbsolute, out var apiServerAddress);

Expand Down
4 changes: 4 additions & 0 deletions src/Websites/Sales/src/Bit.Websites.Sales.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
var builder = WebApplication.CreateBuilder(args);

#if BlazorWebAssembly
builder.Configuration.AddClientConfigurations();
#endif

Bit.Websites.Sales.Api.Startup.Services.Add(builder.Services, builder.Environment, builder.Configuration);

var app = builder.Build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@ public static void Add(IServiceCollection services, IWebHostEnvironment env, ICo
.ConfigurePrimaryHttpMessageHandler<AppHttpClientHandler>()
.ConfigureHttpClient((sp, httpClient) =>
{
NavigationManager navManager = sp.GetRequiredService<IHttpContextAccessor>().HttpContext!.RequestServices.GetRequiredService<NavigationManager>();
httpClient.BaseAddress = new Uri($"{navManager.BaseUri}api/");
Uri.TryCreate(configuration.GetApiServerAddress(), UriKind.RelativeOrAbsolute, out var apiServerAddress);
if (apiServerAddress!.IsAbsoluteUri is false)
{
apiServerAddress = new Uri($"{sp.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.GetBaseUrl()}{apiServerAddress}");
}
httpClient.BaseAddress = apiServerAddress;
});
services.AddScoped<Microsoft.AspNetCore.Components.WebAssembly.Services.LazyAssemblyLoader>();

Expand All @@ -41,7 +45,6 @@ public static void Add(IServiceCollection services, IWebHostEnvironment env, ICo
// for other usages of httpclient, for example calling 3rd party apis, either use services.AddHttpClient("NamedHttpClient") or services.AddHttpClient<TypedHttpClient>();
});
services.AddRazorPages();
services.AddMvcCore();
#endif
services.AddHttpClient<TelegramBotApiClient>();
services.AddScoped<TelegramBotService>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ namespace Microsoft.AspNetCore.Http;

public static class HttpRequestExtensions
{
/// <summary>
/// https://blog.elmah.io/how-to-get-base-url-in-asp-net-core/
/// </summary>
public static string GetBaseUrl(this HttpRequest req)
{
var uriBuilder = new UriBuilder(req.Scheme, req.Host.Host, req.Host.Port ?? -1);
if (uriBuilder.Uri.IsDefaultPort)
{
uriBuilder.Port = -1;
}

return uriBuilder.Uri.AbsoluteUri;
}

public static bool ShouldRenderStaticMode(this HttpRequest request)
{
var agent = GetLoweredUserAgent(request);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Reflection;

namespace Microsoft.Extensions.Configuration;

public static class IConfigurationBuilderExtensions
{
public static void AddClientConfigurations(this IConfigurationBuilder builder)
{
var assembly = Assembly.Load("Bit.Websites.Sales.Web");
builder.AddJsonStream(assembly.GetManifestResourceStream("Bit.Websites.Sales.Web.appsettings.json")!);
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
namespace Microsoft.Extensions.Configuration;
//-:cnd:noEmit
namespace Microsoft.Extensions.Configuration;
public static class IConfigurationExtensions
{
public static string GetApiServerAddress(this IConfiguration configuration)
{
return configuration.GetValue<string?>("ApiServerAddress") ?? throw new InvalidOperationException("Could not find ApiServerAddress config");
var apiServerAddress = configuration.GetValue("ApiServerAddress", defaultValue: "api/")!;

return Uri.TryCreate(apiServerAddress, UriKind.RelativeOrAbsolute, out _) ? apiServerAddress : throw new InvalidOperationException($"Api server address {apiServerAddress} is invalid");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public static WebApplication CreateHostBuilder(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonStream(typeof(MainLayout).Assembly.GetManifestResourceStream("Bit.Websites.Sales.Web.appsettings.json")!);
builder.Configuration.AddClientConfigurations();

Startup.Services.Add(builder.Services, builder.Configuration);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,9 @@ public partial class Program
public static WebAssemblyHost CreateHostBuilder(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault();
builder.Configuration.AddJsonStream(typeof(MainLayout).Assembly.GetManifestResourceStream("Bit.Websites.Sales.Web.appsettings.json"));
builder.Configuration.AddClientConfigurations();

if (Uri.TryCreate(builder.Configuration.GetApiServerAddress(), UriKind.RelativeOrAbsolute, out var apiServerAddress) is false)
{
throw new InvalidOperationException("Api server address is invalid");
}
Uri.TryCreate(builder.Configuration.GetApiServerAddress(), UriKind.RelativeOrAbsolute, out var apiServerAddress);

if (apiServerAddress.IsAbsoluteUri is false)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ public static class Services
{
public static void Add(IServiceCollection services, IConfiguration configuration)
{
Uri.TryCreate(configuration.GetApiServerAddress(), UriKind.Absolute, out var apiServerAddress);
services.AddScoped(sp =>
{
HttpClient httpClient = new(sp.GetRequiredService<AppHttpClientHandler>())
{
BaseAddress = new Uri(sp.GetRequiredService<IConfiguration>().GetApiServerAddress())
BaseAddress = apiServerAddress
};

return httpClient;
Expand Down

0 comments on commit 2342898

Please sign in to comment.