Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make custom ApplicationName work for hosting and user secrets #52305

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions src/DefaultBuilder/src/WebApplicationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -275,15 +275,13 @@ private static void ApplyDefaultAppConfigurationSlim(IHostEnvironment env, Confi

if (env.IsDevelopment() && env.ApplicationName is { Length: > 0 })
{
try
var appAssembly = GetAppAssembly(env.ApplicationName);

// If the assembly cannot be found, so just skip it.
if (appAssembly is not null)
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
configuration.AddUserSecrets(appAssembly, optional: true, reloadOnChange: reloadOnChange);
}
catch (FileNotFoundException)
{
// The assembly cannot be found, so just skip it.
}
}

configuration.AddEnvironmentVariables();
Expand All @@ -306,6 +304,18 @@ static bool GetReloadConfigOnChangeValue(ConfigurationManager configuration)
}
return result;
}

static Assembly? GetAppAssembly(string applicationName)
{
try
{
return Assembly.Load(new AssemblyName(applicationName));
}
catch
{
return Assembly.GetEntryAssembly();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In unit tests this can be testhost, but that's no problem as the user secrets are reigstered as optional, thus if the attribute for user sectes doesn't exist, it's just ignored.

Besides that is there any other reliable way to probe for existance of an assembly?

}
}
}

private static void AddDefaultServicesSlim(ConfigurationManager configuration, IServiceCollection services)
Expand Down
19 changes: 16 additions & 3 deletions src/Hosting/Hosting/src/Internal/WebHostOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public WebHostOptions(IConfiguration primaryConfiguration, IConfiguration? fallb
PreferHostingUrls = WebHostUtilities.ParseBool(GetConfig(WebHostDefaults.PreferHostingUrlsKey));

// Search the primary assembly and configured assemblies.
HostingStartupAssemblies = Split(ApplicationName, GetConfig(WebHostDefaults.HostingStartupAssembliesKey));
HostingStartupAssemblies = Split(GetHostingStartupAssemblyName(ApplicationName), GetConfig(WebHostDefaults.HostingStartupAssembliesKey));
HostingStartupExcludeAssemblies = Split(GetConfig(WebHostDefaults.HostingStartupExcludeAssembliesKey));

var timeout = GetConfig(WebHostDefaults.ShutdownTimeoutKey);
Expand Down Expand Up @@ -77,16 +77,29 @@ public IEnumerable<string> GetFinalHostingStartupAssemblies()
private static IReadOnlyList<string> Split(string? value)
{
return value?.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
?? Array.Empty<string>();
?? [];
}

private static IReadOnlyList<string> Split(string applicationName, string? environment)
{
if (string.IsNullOrEmpty(environment))
{
return new[] { applicationName };
return [applicationName];
}

return Split($"{applicationName};{environment}");
}

private static string GetHostingStartupAssemblyName(string applicationName)
{
try
{
_ = Assembly.Load(new AssemblyName(applicationName));
return applicationName;
}
catch
{
return Assembly.GetEntryAssembly()?.GetName().Name ?? "";
}
}
}
18 changes: 18 additions & 0 deletions src/Hosting/Hosting/test/WebHostBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,24 @@ public void DefaultApplicationNameWithUseStartupFactory(IWebHostBuilder builder)
}
}

[Theory]
[MemberData(nameof(DefaultWebHostBuilders))]
public void CustomApplicationName(IWebHostBuilder builder)
{
const string AppName = "MyApp";

using (var host = builder
.UseServer(new TestServer())
.UseStartup<Startup>()
.UseSetting(WebHostDefaults.ApplicationKey, AppName)
.Build())
{
var hostingEnv = host.Services.GetService<IHostEnvironment>();

Assert.Equal(AppName, hostingEnv.ApplicationName);
}
}

[Theory]
[MemberData(nameof(DefaultWebHostBuilders))]
public void Configure_SupportsNonStaticMethodDelegate(IWebHostBuilder builder)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,19 @@ public async Task DefaultEnvironment_Is_Development()
Assert.Equal(expected, content);
}

[Fact]
public async Task DefaultApplicationName_Is_Name_Of_EntryAssembly()
{
// Arrange
var expected = typeof(SimpleWebSiteWithWebApplicationBuilder.Program).Assembly.GetName().Name;

// Act
var content = await Client.GetStringAsync("http://localhost/appname");

// Assert
Assert.Equal(expected, content);
}

[Fact]
public async Task Configuration_Can_Be_Overridden()
{
Expand Down Expand Up @@ -192,6 +205,25 @@ public async Task Environment_Can_Be_Overridden()
Assert.Equal(expected, content);
}

[Fact]
public async Task ApplicationName_Can_Be_Overridden()
{
// Arrange
var fixture = _fixture.WithWebHostBuilder(builder =>
{
builder.UseSetting(WebHostDefaults.ApplicationKey, "MyApp");
});

var expected = "MyApp";
using var client = fixture.CreateDefaultClient();

// Act
var content = await client.GetStringAsync("http://localhost/appname");

// Assert
Assert.Equal(expected, content);
}

[Fact]
public async Task WebRoot_Can_Be_Overriden()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@

app.MapGet("/problem", () => Results.Problem("Some problem"));

app.MapGet("/appname", (IHostEnvironment environment) => environment.ApplicationName);
app.MapGet("/environment", (IHostEnvironment environment) => environment.EnvironmentName);
app.MapGet("/webroot", (IWebHostEnvironment environment) => environment.WebRootPath);

Expand Down
Loading