I have looked at this guide and have done what is described etc. But it's like that when I run my "API (dev)" it throws the contents into the database which is live. But in principle it should not do that. It should throw it into database_test but it does not.
Thus, when I run over in "API (prod)", it fails and I can thus not be allowed to throw things into the database.
appsettings.Development.json
"ConnectionStrings": {
"Db": "xxxx"<--- Test database
}
appsettings.json
"ConnectionStrings": {
"Db": "xxxx"<--- Live database
}
launchSettings.json
{
xxxx,
"profiles": {
xxxxx,
"API (prod)": {
"commandName": "Project",
"launchBrowser": false,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
},
"applicationUrl": "https://localhost:8082;http://localhost:8444",
"dotnetRunMessages": "true"
},
"API (dev)": {
"commandName": "Project",
"launchBrowser": false,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:8081;http://localhost:8443",
"dotnetRunMessages": "true"
},
xxxxx
}
}
Startup.cs
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.Development.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
The problem is just that it throws it into the live database when I run dev, but then it throws the contents of the live database but I only want it to throw it into the test database. And when it's live, it's going to throw it in the live database.
EIDT - UPDATE.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("xxxxx");
}
}
have found that this is why I can not use test. So now I just have to figure out how I can get it done so that it makes use of testing when I dev and live when it's up.
CodePudding user response:
Based on the guide you link to, you shouldn't need any explicit loading of the app settings files. It will, by default, load the appsettings.json
and appsettings.<Environment>.json
automatically. It will also automatically load any environment variables with an ASPNETCORE_
prefix it finds. (or DOTNET_
for generic hosts)
I would remove the redundant code. let the builder do its job, and ensure the environment variables are set and available when your app starts. If you can't find or get any value or the value you expect with Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
then something's wrong with how they're being set.
Also, appsettings.json
will load regardless of any issues with missing vars if it's present so I wouldn't put the production connection string there. Rather, put your local or dev connection string there and let the production value overwrite the dev/default value so you don't accidentally default to production.