Using the first-ever template that I created in dotnet new
, I generated a solution in Visual Studio 2022 with an ASP.NET Core Web API project; this project contains an appsettings.json
file and a controller with a GET
action, which retrieves a company with a name property:
public class Company
{
public in ID { get; init; }
public string Name { get; init }
}
I have a staging and a production SQL database.
The staging database has a company with the name "StagingCompany". The production database has a company with the name "ProductionCompany".
I first test the Web API using a connection string to my staging database, and I GET
the company named "StagingCompany" as I would expect.
However, when I change the connection string to point to my production database, I still GET
the company named "StagingCompany" when I was expecting to get "ProductionCompany". When I debug my code, I can see that the desired production connection string is being loaded during the Program.cs
dependency injection, so I don't believe this is an issue of my appsettings.json
connection string being overridden by another connection string from some other mysterious config file:
builder.Services.AddDbContext<CompanyContext>(options =>
{
options.UseSqlServer(builder.Configuration["ConnectionStrings:Company"], //the connection string loaded here is correct
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name);
sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
});
});
The appsettings.json looks like this:
"ConnectionStrings": {
"Company": "Server=Address;Initial Catalog=Company;Persist Security Info=True;User ID=id;Password=password;Connect Timeout=120"
}
I searched for any potential config files within the solution that could interfere with appsettings.json
. I confirmed that I'm not using any User Secrets. I confirmed that the correct connection string was being loaded during the dependency injection.
I expected the ASP.NET Core Web API to create a connection with the production database using the production connection string that was loaded during the dependency injection, but it instead connected to the staging database.
I've never had this problem before, so it must have something to do with the dotnet new
template being used. If the desired connection string is being read and loaded during dependency injection, why is it not being used? Is it possible for a former "cached" connection to override the current one?