Ask Your Question
2

How can I retrieve the value of the launch profile in .NET Core at runtime?

asked 2023-07-19 16:45:04 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-19 16:55:02 +0000

djk gravatar image

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).

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-19 16:45:04 +0000

Seen: 12 times

Last updated: Jul 19 '23