I am porting my .Net Framework webjobs to Core v6 and creating them afresh as console apps. I'm having trouble getting the connection string on the parent web app in Azure to override the connection string on the webjob.
And then I have appsettings.json in the webjob, which is set to Copy If Newer:
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=localhost;Initial Catalog=x;Persist Security Info=True;Integrated Security=True;TrustServerCertificate=True"
}
}
And then I read out the connection string in Program.cs, but it's showing the local connection string rather than from the webapp:
using Microsoft.Extensions.Configuration;
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: false);
var configuration = builder.Build();
var connectionString = configuration.GetSection("ConnectionStrings")["DefaultConnection"];
throw new Exception(connectionString);
Here is the logging from the webjob on Azure:
[03/08/2024 19:04:00 > 65f818: SYS INFO] Status changed to Initializing
[03/08/2024 19:04:00 > 65f818: SYS INFO] Run script 'run.cmd' with script host - 'WindowsScriptHost'
[03/08/2024 19:04:00 > 65f818: SYS INFO] Status changed to Running
[03/08/2024 19:04:00 > 65f818: INFO]
[03/08/2024 19:04:00 > 65f818: INFO] C:\local\Temp\jobs\triggered\Test\qahcfbvl.0q4>dotnet xxx.dll
[03/08/2024 19:04:00 > 65f818: ERR ] Unhandled exception. System.Exception: Data Source=localhost;Initial Catalog=x;Persist Security Info=True;Integrated Security=True;TrustServerCertificate=True
[03/08/2024 19:04:00 > 65f818: ERR ] at Program.<Main>$(String[] args) in C:\Dev\xxx\Program.cs:line 16
[03/08/2024 19:04:00 > 65f818: SYS INFO] Status changed to Failed
[03/08/2024 19:04:00 > 65f818: SYS ERR ] Job failed due to exit code -532462766
The Environmental Variables added in the Azure App service are accessible when you add .AddEnvironmentVariables()
in the code.
Install the NuGet package Microsoft.Extensions.Configuration.EnvironmentVariables
.
I am able to retrieve the Connection String by using configuration.GetConnectionString("DefaultConnection")
as well.
My Program.cs
file:
using Microsoft.Extensions.Configuration;
Console.WriteLine("Hello, World!");
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false)
.AddEnvironmentVariables();
var configuration = builder.Build();
var connectionString = configuration.GetSection("ConnectionStrings")["DefaultConnection"];
//var azureconn = configuration.GetConnectionString("DefaultConnection");
throw new Exception(connectionString);
Local Output:
Environment Variable :
Web Job Output: