Reputation: 2270
This ASP.NET Core 3.1 application works fine on the local machine, but when hosted in Azure App Service it does not use the configuration variables set under "Application settings".
The following variables have been created inside of the App Service configuration with the same values set in appsettings.json
:
How can the controller file method below be changed to use the appsettings.json
file locally, and the Azure App service configuration settings in the cloud? appsettings.json
is not being included in the repository in Azure DevOps that is built and deployed to Azure App Service.
private void InitSearch()
{
// Create a configuration using the appsettings file.
_builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
_configuration = _builder.Build();
// Pull the values from the appsettings.json file.
string searchServiceName = _configuration["SearchServiceName"];
string queryApiKey = _configuration["SearchServiceQueryApiKey"];
// Create a service and index client.
_serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(queryApiKey));
_indexClient = _serviceClient.Indexes.GetClient("example-index");
}
{
"SearchServiceName": "example-search-service",
"SearchServiceQueryApiKey": "example-query-api-key",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Upvotes: 4
Views: 5417
Reputation: 2270
This worked. "IWebHostEnvironment" must be brought into the controller class using a dependency injection pattern.
public class MyController : Controller
{
private readonly IWebHostEnvironment _environment;
public MyController(IWebHostEnvironment env)
{
this._environment = env;
}
private void InitSearch(IWebHostEnvironment env)
{
// Create a configuration using the appsettings file.
_builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
_configuration = _builder.Build();
// Pull the values from the appsettings.json file.
string searchServiceName = _configuration["SearchServiceName"];
string queryApiKey = _configuration["SearchServiceQueryApiKey"];
// Create a service and index client.
_serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(queryApiKey));
_indexClient = _serviceClient.Indexes.GetClient("example-index");
}
}
Upvotes: 0
Reputation: 93053
The configuration settings set in an Azure App Service are provided to the app itself using environment variables. With that in mind, you can just add the environment-variable provider to your ConfigurationBuilder
, like this:
_builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
See Override app configuration using the Azure Portal for more information.
Upvotes: 2