When I hardcode my connection string into my project, it works just fine, Also, Azure Key Vault works just fine when in running in release mode. However, when I try to use the Secrets.json, some endpoints still work, but others return this error:
System.InvalidOperationException: The ConnectionString property has not been initialized.
at Microsoft.Data.SqlClient.SqlConnection.PermissionDemand()
at Microsoft.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
at Microsoft.Data.SqlClient.SqlConnection.InternalOpenAsync(CancellationToken cancellationToken)
As I mentioned hardcoding the URL works fine, and running in release works fine also,
Here's what I have in my Program.cs:
var builder = WebApplication.CreateBuilder(args);
#if DEBUG
builder.Configuration.AddUserSecrets<Program>();
#else
var vaultUri = Environment.GetEnvironmentVariable("VaultUri");
var keyVaultEndpoint = new Uri(vaultUri);
builder.Configuration.AddAzureKeyVault(keyVaultEndpoint, new DefaultAzureCredential());
#endif
and in my db context:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
#if DEBUG
string connectionString = _configuration.GetConnectionString("HomeDatabase");
#else
string connectionString = _configuration.GetConnectionString("AzureDatabase");
#endif
optionsBuilder.UseSqlServer(connectionString);
}
I have tried setting a breakpoint and it seems that for some reason, when in debug, the string sets correctly, but for some reason, after hitting step over a thousand times, it jumps back into the "string connectionString = _configuration.GetConnectionString("HomeDatabase");" line at which point the connectionString suddenly becomes null...
Just to add, it seems the simple endpoints work, but if my dbcontxt gets called a second time, that's when the connection string goes null.
if anyone has any ideas, I'd be very grateful.
Thank you. :)
EDIT~~~~~~~~~~~~~~~~~~~
after playing around some more, going to the trouble of creating a new database with a new db context just to handle the tokens. as soon as i added the secrets, again I'm getting the null error...
it seems that the secrets are held up until whichever context is using them has finished.
I figured it out in the end. I had an authorization handler and a middleware that were conflicting. Fixed it by removing the middleware and having the custom authorization handler handle everything.