Я развернул приложение-функцию Azure в Linux с помощью .NET 8 (dotnet-isolated).
При настройке конфигурации приложения я начинаю с установки базового пути с помощью Directory.GetCurrentDirectory().
Однако во время выполнения (только Azure, а не локально!) файл appsettings.json найти невозможно. Сгенерированный путь представляет собой комбинацию Windows и Linux: '/tmp/functions\standby\wwwroot/appsettings.json'
Почему я наблюдаю такое поведение и как можно это можно исправить?
Ошибка:
Unhandled exception. System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The expected physical path was '/tmp/functions\standby\wwwroot/appsettings.json'.
Код:
var host = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureAppConfiguration(builder =>
{
var environment = Environment.GetEnvironmentVariable("ENVIRONMENT") ?? "development";
builder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
})
...
Код функции:
using System.Configuration;
using System.Xml.Serialization;
using Azure.Identity;
using Azure.Storage.Queues;
using Microsoft.Azure.Functions.Worker;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
var connectionString = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING");
if (!string.IsNullOrEmpty(connectionString))
{
builder.AddApplicationInsights(
configureTelemetryConfiguration: (config) => config.ConnectionString = connectionString,
configureApplicationInsightsLoggerOptions: (options) => { }
);
}
});
var logger = loggerFactory.CreateLogger("Startup");
try
{
var host = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureAppConfiguration(builder =>
{
var environment = Environment.GetEnvironmentVariable("ENVIRONMENT") ?? "development";
builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
})
.ConfigureServices((context, services) =>
{
services.AddApplicationInsightsTelemetryWorkerService();
services.ConfigureFunctionsApplicationInsights();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddDbContext(options =>
{
var connectionString = context.Configuration.GetConnectionString("SqlServer") ?? throw new ConfigurationErrorsException("Connection string not found: SqlServer");
logger.LogInformation("Connection string: {connectionString}", connectionString);
options.UseSqlServer(connectionString);
});
services.AddScoped(sp =>
{
var connectionString = context.Configuration.GetValue("AzureWebJobsStorage") ??
throw new ConfigurationErrorsException("Configuration value not found: AzureWebJobsStorage");
var queueNane = context.Configuration.GetValue("OwnerNotificationsQueueName") ??
throw new ConfigurationErrorsException("Configuration value not found: OwnerNotificationsQueueName");
var queueClient = new QueueClient(connectionString, queueNane);
queueClient.CreateIfNotExists();
return new QueueService(queueClient);
});
services.AddScoped();
services.AddScoped();
services.AddTransient();
services.AddSingleton(sp =>
{
var managedIdentityClientId = context.Configuration.GetValue("ManagedIdentityClientId");
if (managedIdentityClientId != null)
{
// User-assigned managed identity
var defaultCredentialOptions = new DefaultAzureCredentialOptions { ManagedIdentityClientId = managedIdentityClientId };
return new GraphServiceClient(new DefaultAzureCredential(defaultCredentialOptions));
}
// System-assigned managed identity
return new GraphServiceClient(new DefaultAzureCredential());
});
})
// .ConfigureLogging(builder =>
// {
// builder.Services.Configure(options =>
// {
// LoggerFilterRule defaultRule = options.Rules.FirstOrDefault(rule => rule.ProviderName
// == "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider");
// if (defaultRule is not null)
// {
// options.Rules.Remove(defaultRule);
// }
// });
// })
.Build();
await host.RunAsync();
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred: {message}", ex.Message);
throw;
}
.csproj:
net8.0
v4
Exe
enable
enable
PreserveNewest
PreserveNewest
Never
PreserveNewest
PreserveNewest
Never
Подробнее здесь: https://stackoverflow.com/questions/790 ... d-path-mix