[英]How to configure Azure App Service logging provider for an ASP.NET Core app?
[英]How to configure Azure App Service application settings for ASP.NET Core 3.1?
此 ASP.NET Core 3.1 應用程序在本地計算機上運行良好,但在 Azure App Service 中托管時,它不使用“應用程序設置”下設置的配置變量。
以下變量已在 App Service 配置中創建,其值與appsettings.json
中設置的值相同:
下面的controller file方法如何改成本地使用appsettings.json
文件,雲端的Azure App服務配置設置? appsettings.json
未包含在構建並部署到 Azure 應用服務的 Azure DevOps 存儲庫中。
私有無效 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": "*"
}
Azure 應用服務中設置的配置設置使用環境變量提供給應用本身。 考慮到這一點,您只需將環境變量提供程序添加到您的ConfigurationBuilder
,如下所示:
_builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
有關詳細信息,請參閱使用 Azure 門戶覆蓋應用程序配置。
這奏效了。 必須使用依賴注入模式將“IWebHostEnvironment”引入控制器類。
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");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.