3
votes

I manage to have different Environments in web application. In development environment I need to work on different database connection. I tried to manage on next way but unfortunately doesn't works. appsettings.Development.json

  {
  "ConnectionStrings": {
    "DefaultConnection": "Server=xxx.xx.xxx.xxx;Database=dbName;User Id=xxPassword=xxxxxxx;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

appsettings.json

 {
  "ConnectionStrings": {
    "DefaultConnection": "Server=xxx.xx.xxx.xxx;Database=dbName;User Id=xxPassword=xxxxxxx;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Startup.cs

public IHostingEnvironment environment;

public Startup(IHostingEnvironment env)
{

    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    if (environment.IsDevelopment())
    {
        services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }
    else if (environment.IsProduction())
    {
        services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }


    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    // Add application services.
    services.AddTransient<IEmailSender, EmailSender>();
    services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
    services.AddTransient<DbInitializer>();


    services.AddMvc();
}

With my code I'm getting an error when I start app. An error occurred while starting the application.

General idea is when I'm in development environment to use appsettings.Development.json

4

4 Answers

2
votes

you need to set your variabele. And then you create aditional appsettings..json files.

So you probarly already have you appsetings.json We generally create also a appsettings.test.json and a appsettings.prod.json.

With this code in in the startup class, in the constructor:

public Startup(IHostingEnvironment env, ILogger<Startup> logger)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", true, true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();

        _logger = logger;

        _logger.LogInformation($"Env: {env.EnvironmentName}");
    }

you see this line: .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)

this one will overwrite the existing settings. For example; if you host your app in azure, you need to set an application-setting with ASPNETCORE_ENVIRONMENT with test or prod..

or offcourse you can set it on the property tab of your project

cheers!

1
votes

It's looks that you do not set ASPNETCORE_ENVIRONMENT variable to Development and uses config file $"appsettings.{env.EnvironmentName}.json" as required (optional: false)

If you run application from command line you need to set up this variable.

For CMD:

set ASPNETCORE_ENVIRONMENT=Development

For powershell:

$Env:ASPNETCORE_ENVIRONMENT = "Development"

If you are running project from Visual Studio, you can set this variable on "Debug" tab of project properties. You just need to add this environment variable using UI.

0
votes

Here is code which is solving my problem.

private IHostingEnvironment _env;

        public Startup(IHostingEnvironment env)
        {
            _env = env;


            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();

        }
0
votes

For as far as I know the EnvironmentName is being set in the project's "Environment variables".

  • Right-click on the project.
  • Properties.
  • Go to the Debug tab.
  • Change the value of "ASPNETCORE_ENVIRONMENT" to "Development".

Rebuild and appsettings.Development.json should be used.

Environment variables

Or on Azure:

  • Go to your app
  • click "Application settings"
  • Under the title "App settings" you can add "ASPNETCORE_ENVIRONMENT"