Reputation: 1833
I have 2 projects 1.ASP.NET Core WEB API 2. Azure function
Both are hosted on a azure. I also have different accounts for development and production, hense I need to have different connection strings depending on environment the application are deployed on.
For entity framework I use a separate project which the 2 application refer to.
Whene the separate project is used from weba api I can read a connection string this way
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{envName}.json", optional: false)
.Build();
var cs = configuration.GetConnectionString("DefaultConnection");
optionsBuilder.UseSqlServer(cs);
}
}
But there's no appsettings.json file for trigger. What can I do in this case?
Upvotes: 1
Views: 906
Reputation: 3612
For Local Development use an Environment Variable
to store your connection string.
(Right click your Azure Function Project
in Visual Studio
select properties
, Debug
and you will be able to add an Environment Variable
there. This will be stored in launchsettings.json
)
For example you could call it MSSQL_CONN_STR
When Deployed to Azure
use Application Settings
(Goto Function app
click Configuration
and you can add a new Application Setting/Environment variable with the same key as above (MSSQL_CONN_STR
) but with your production
value for the connection string)
In your C# code you can get the Environment Variable
the same as you have above
Environment.GetEnvironmentVariable("MSSQL_CONN_STR");
From MS regarding Application Settings for Azure Function App
Application Settings are exposed as environment variables for access by your application at runtime
Upvotes: 1