1 | initial version |
You can retrieve the launch profile value in .NET Core at runtime by using the IWebHostEnvironment
interface, which provides information about the application environment.
Here's an example:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
public class ExampleClass
{
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _environment;
public ExampleClass(IConfiguration configuration, IWebHostEnvironment environment)
{
_configuration = configuration;
_environment = environment;
}
public void GetLaunchProfileValue()
{
var launchProfile = _configuration.GetSection("profiles")
.Get<LaunchProfile>()
.FirstOrDefault(p => p.Key == _environment.EnvironmentName);
// Launch profile value can be accessed through "launchProfile.Value" property
}
}
public class LaunchProfile
{
public string Key { get; set; }
public LaunchValue Value { get; set; }
}
public class LaunchValue
{
public string ApplicationUrl { get; set; }
public bool LaunchBrowser { get; set; }
public string LaunchUrl { get; set; }
}
In the above example, we're injecting IConfiguration
and IWebHostEnvironment
in the constructor of our ExampleClass
. We then use the GetLaunchProfileValue
method to retrieve the launch profile value.
The IConfiguration
is used to get the launch profiles. We retrieve all the launch profiles using GetSection("profiles")
, and then filter the launch profile that matches our current environment name (which is retrieved using _environment.EnvironmentName
). We then access the launch profile value through the Value
property.
Note: This example assumes that you have defined a launch profile in your launchSettings.json
file, and that you've set the environment name in your launchSettings.json
file to match the environment name of your application (ASPNETCORE_ENVIRONMENT
environment variable).