I am migrating from .NET Core 5.0 to 6.0.
The following piece of code works just fine in 6.0.
builder.Services.AddDbContext<QuoteCMSContext>(options =>
options.UseSqlite("Data Source=quotesdatabase.db"));
Now, in my old 5.0 project, I had something like this.
//database context
services.AddDbContext<QuoteCMSContext>(options =>
options.UseSqlite(Configuration["SqliteConnectionString"]));
I looked at all these other questions, which appear to deal with my problem.
ASP.NET Core 6 how to access Configuration during startup
Getting value from appsettings.json in .net core
ConnectionString in .NET Core 6
Eventually, I came up with this.
builder.Services.AddDbContext<QuoteCMSContext>(options =>
options.UseSqlite(builder.Configuration["SQLiteConnectionString"]));
and this
builder.Services.AddDbContext<QuoteCMSContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("SQLiteConnectionString")));
in both cases, I keep getting null exceptions. I dont' know what I am missing.
Here is my appsettings.json, just in case.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"SQLiteConnectionString": "Data Source=quotesdatabase.db",
"AzureSqlServerConnectionString": "Server=tcp:.database.windows.net,1433;Initial Catalog=DBName;Persist Security Info=False;User ID=;Password=;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
"CorsOriginLocalHost": "http://localhost:3000",
"CorsOriginStaging": "https://randomstuffreactjsappzeropoint4.azurewebsites.net",
"CorsOriginProduction": "https://randomstuffreactjsappzeropoint4.azurewebsites.net",
"ConnectionStrings": {
"SQLiteConnectionString": "Data Source=quotesdatabase.db"
}
}
Update 1 :
I noticed something odd. The following code, does not raise any errors. Actually, sorry, I wasn't injecting cors in my code yet. This also gives the same null error. So, yes, at this point, definitely not able to read information from appsettings.json
builder.Services.AddCors(cors =>
{
cors.AddDefaultPolicy( policy =>
{
policy.WithOrigins(builder.Configuration["CorsOriginLocalHost"],
builder.Configuration["CorsOriginStaging"],
builder.Configuration["CorsOriginProduction"]);
//policy.WithOrigins("http://localhost:3000",
// "http://localhost:3000"
// );
policy.AllowAnyMethod();
policy.AllowAnyHeader();
policy.AllowCredentials();
}
);
}
);
Update 2 :
Okay, I found the problem. I had changed the 'Working Directory' while debugging SQLite. So, the code kept looking for appsettings.json in the wrong location. I set to the project folder manually. I used to do this step in .NET 5.0.
Looks like it's not required in .NET 6.0
I went back to project properties and removed the path I had set. made it blank. Now, able to read appsettings.json.