How to read variables from ASP.Net Core Multiple Environments?

Asked

Viewed 269 times

1

I’m trying to read from the properties appsettings file with different values, one for each environment. My files are as follows, appsettings.json, appsettings.Development.json, appsettings.Stage.json in case the system recognizes who the environment is working on and accesses the correct file, this part is working by which otherwise the system in the non working Stage environment as well as in the production environment for the customer. So this is not the problem, my problem is the following was developing and worked perfectly in the Development environment, but when I went to Stage, it did not work.

I have these codes currently:

appsettings.json:

"StringsConnection": {
    "canal": "plataforma-production",
    "link": "781115465H/1Tasdsdaaaa/K456546bb45654665fdg"
}

appsettings.Development.json:
"StringsConnection": {
    "canal": "plataforma-local",
    "link": "484ghj6ngfh/jg468fgh/dfg468df4g6864sdf84ds"
  },

appsettings.Stage.json:

"StringsConnection": {
    "canal": "plataforma-stage",
    "link": "dsf546/DSF86SD4F4DS/SAD6S8A4DSAdsf84dsa"
}

I am accessing the properties "channel" and "link"

apiControlerQualquer.Cs:

var canal= new collector_log
            {
                log = _config.GetValue<string>(
                   "ConnectionStrings:canal")
            };

var link= new collector_log
            {
                log = _config.GetValue<string>(
                "ConnectionStrings:link")
            };

in the controller I still have

  private readonly ApplicationDbContext _context;
    private readonly IMapper _mapper;
    private readonly IConfiguration _config;

    public Methods_Utils(ApplicationDbContext context, IMapper mapper, IConfiguration config)
    {
        _context = context;
        _mapper = mapper;
        _config = config;
    }

Startup.Cs:

public class Startup
    {
        //injeção de depencencias
        HelperController helper = new HelperController();

        public IConfiguration Configuration { get; private set; }
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {    
            var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
               .AddEnvironmentVariables();
            Configuration = builder.Build();
            this.Configuration = configuration;
        }

Program.Cs

public class Program
{        
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();          
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
       WebHost.CreateDefaultBuilder(args)
           .UseStartup<Startup>()
          .ConfigureLogging((hostingContext, logging) =>
          {
              logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
              logging.AddConsole();
              logging.AddDebug();
              logging.AddEventSourceLogger();
          });              
}

The point is, I’m being able to access the values in the Development environment however, I’m not being able to access the values in the Stage environment, if anyone can help thank you.

  • After all it is working or not!? One minute says yes, another says no... You can’t understand. What comes to be "I’m not being able to access the values in the Stage environment"? Even in the te environmentThe values are those of Development, that’s it?

  • I don’t think I explained it very well, I can get into the Velopment, and I can’t get into the Stage. In other words in the Stage environment I’m having problems, I’m not able to access the value!

  • And how are you getting started? What is the value of ASPNETCORE_ENVIRONMENT?

  • The application is normally initializing without error. No Visual Studio na aba Project no oção API Properties depois na aba Debug esta informando o seguinte: ASPNETCORE_ENVIRONMENT = Development

  • If it is not set as an environment variable or via command line, the default value is Production. Since VS has this setting, qndo runs the application with VS, the environment is used Development and therefore the appsettings.Development.json. In other cases, the appsettings.Production.json, if it exists. I don’t see how you intend to use the appsettings.Stage.json. At least not made it clear in the question. It is not possible to know whether it is on your machine, for testing, or on another machine. Not even if the proper configs are made or if the way to read the configs in the app has been changed.

  • The appsettings configuration is working, the server recognizes the appropriate environments. But what I’m not able to do is the following: in Stage environment the variables I set in appsettings.stage.json are not recognized, taking into account that it is the same as in appsettings.development.json.

  • Works normally in dev environment, but when I commit to Stage, it no longer works, remembering that Stage is on the AWS server.

  • It’s like I explained above. On your machine it will work like Development because of this VS. In Stage, you need to add the environment variable. Doing this will depend on how you are using AWS (if some "as a service" of them or virtual machine) and which OS.

  • Already the environment variable is configured and I am using Kubernets and Docker with Linux OS.

  • One point of attention is that linux is case sensitive. Check the file name appsettings.Stage.json and the value of ASPNETCORE_ENVIRONMENT in your container.

  • The file name appsettings.Stage.json and the value of ASPNETCORE_ENVIRONMENT have been checked and this is correct.

  • Since this part is ok, then add to your question the.Cs program and startup.Cs (the relevant parts, if any), PF.

  • Ready, added the codes of Program.Cs and Startup.Cs

  • Can download your container and confirm that the file Stage is present? Another option would be to make a test by removing the optional: true of AddJsonFile, to check whether the error application at start.

  • .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)

  • Thank you very much for trying to help me, I finally solved the problem, I was connected to another part of the system, a function to catch ip was not working, there was error there, and the system stopped there, did not proceed until the part I developed, I really thought it was a problem in the environment variables, even because I had not even touched this function of catching the ip, but now I’ve solved. Many thanks to everyone and especially pro tvdias.

Show 11 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.