我正在将一个 azure 函数迁移到 web 作业,以完成它所花费的时间。
之前的旧代码使用
Environment.GetEnvironmentVariable("CosmosDbAccountEndpoint");
并且它是从 local.settings.json 读取的,但正如我所读的那样,Webjob 是一个控制台应用程序,因此它应该从应用程序设置中获取这些值。但是部署时如何使用 Azure 门户中存在的环境变量?
我看过https://learn.microsoft.com/en-us/azure/app-service/webjobs-sdk-get-started
这里说要为连接字符串创建 appsettings.json 但我不明白如何获取变量
有什么建议吗?
这是我的程序.cs
// See https://aka.ms/new-console-template for more information
using AzFunctions.SerilogEnrichers;
using AzFunctions.Services;
using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Extensions.Logging;
var builder = new HostBuilder();
builder.ConfigureServices(services =>
{
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", true)
.AddEnvironmentVariables("TTG_")
.Build();
services.AddScoped<xxx>();
services.AddHttpClient("xxx", (client) =>
{
var basePath = configuration.GetSection("xxx").GetValue<string>("FHBasePath");
client.BaseAddress = new Uri(basePath);
});
services.AddSingleton<ILoggerProvider>((sp) =>
{
//bool.TryParse(Environment.GetEnvironmentVariable("Seq:Enabled"), out bool seqEn);
//var seqHost = Environment.GetEnvironmentVariable("Seq:ServerUrl");
//var sqeApiKey = Environment.GetEnvironmentVariable("Seq:ApiKey");
var logConfiguration = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.With<RemoveAzureUselessEventPropertiesEnricher>()
.Enrich.WithProperty("ApplicationName", "Azure Functions - Fareharbor sync");
//if (seqEn)
//{
// logConfiguration.WriteTo.Seq(seqHost, apiKey: sqeApiKey);
//}
Log.Logger = logConfiguration.CreateLogger();
return new SerilogLoggerProvider(Log.Logger, true);
});
services.Configure<xxx>(options => configuration.GetSection("xxx").Bind(options));
services.Configure<SeqOptions>(options => configuration.GetSection("Seq").Bind(options));
});
builder.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddHttp();
b.AddTimers();
});
builder.ConfigureLogging((context, b) =>
{
b.SetMinimumLevel(LogLevel.Debug);
var logConfiguration = new LoggerConfiguration()
.WriteTo.Console()
.Enrich.FromLogContext()
.Enrich.With<RemoveAzureUselessEventPropertiesEnricher>()
.Enrich.WithProperty("ApplicationName", "Azure Functions - xxx sync");
// .WriteTo.ApplicationInsights(sp.GetRequiredService<TelemetryClient>(), TelemetryConverter.Traces);
//if (seqEn)
//{
// logConfiguration.WriteTo.Seq(seqHost, apiKey: sqeApiKey);
//}
b.AddSerilog(logConfiguration.CreateLogger());
})
.ConfigureAppConfiguration(b =>
{
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile(
$"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json",
true)
.AddEnvironmentVariables("TTG_")
.Build();
b.AddConfiguration(configuration);
});
var host = builder.Build();
var basePath = Environment.GetEnvironmentVariable("FHBasePath");
await host.RunAsync();
{
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=xxxcore.windows.net",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"TimerSchedule": "0 38 12 * * *",
"CosmosDbAccountEndpoint": "https://xxx.azure.com:443/",
"CosmosDbDatabaseName": "xxxx",
"CosmosDbCollectionName": "item_test",
"CosmosDbAccountKey": "xxx==",
"xxx-US": "xxx",
"xxx-EU": "xxx",
"Seq:Enabled": "True",
"xxx": {
"AccessKey": "xxx",
"xxx": "https://somesite.com",
"xxx": "US,EU",
"Regions": {
"xxx-US": "xxx",
"xxx-EU": "xxx"
},
"Serilog": {
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File",
"Serilog.Sinks.Seq",
"Serilog.Exceptions",
"Serilog.Enrichers.CorrelationId"
],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] {Message}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "%BASEDIR%/Logs/TTG-WebAPI.log",
"rollingInterval": "Day"
}
},
{
"Name": "Seq",
"Args": {
"serverUrl": "https://xxx.azurewebsites.net"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId", "WithExceptionDetails", "WithCorrelationId" ],
"Properties": {
"ApplicationName": "xxx"
}
}
}
}
我读过 Webjob 是一个控制台应用程序,因此它应该从应用程序设置中获取这些值
是的,要运行
Azure WebJobs
,我们需要在Console App
中创建一个Visual Studio
并从那里运行webjobs
。
Console App
.appsettings.json
.CosmosDbAccountEndpoint
文件中检索Azure Functions local.settings.json
值时,我将在CosmosDbAccountEndpoint
文件中设置appsettings.json
的值。我的
appsettings.json
档案:
{
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=xxxcore.windows.net",
"CosmosDbAccountEndpoint": "https://xxx.azure.com:443/",
"ConnectionStrings": {
"xxxDatabase": "Server=tcp:xxxx.database.windows.net,1433;Initial Catalog=xxx;Persist Security Info=False;User ID=xxxx;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
}
右键单击
appsettings.json
文件=>Properties
,将Copy to Output Directory
更改为Copy if newer
.
我的
.csproj
档案:
<Project Sdk="Microsoft.NET.Sdk;Microsoft.NET.Sdk.Publish">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Settings.job">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
我的
Program.cs
档案:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
var configuration = builder.Build();
var cosmosDbAccountEndpoint = configuration.GetValue<string>("CosmosDbAccountEndpoint");
var cosmosDbAccountEndpoint1 = Environment.GetEnvironmentVariable("CosmosDbAccountEndpoint");
Console.WriteLine($"CosmosDbAccountEndpoint = {cosmosDbAccountEndpoint}");
}
}
之前的旧代码是用
Environment.GetEnvironmentVariable("CosmosDbAccountEndpoint");
appsettings.json
中检索值,我使用了以下代码。var cosmosDbAccountEndpoint = configuration.GetValue<string>("CosmosDbAccountEndpoint");
var cosmosDbAccountEndpoint = Environment.GetEnvironmentVariable("CosmosDbAccountEndpoint");
我们需要在
Debug
=> General
=> Environment variables
.中设置值
右键单击
Project Root folder
=>Properties
=>Debug
,添加变量。
本地输出:
部署
Console App
到Azure WebJob
.
继续执行后续步骤以发布应用程序。
部署 Azure 门户中存在的环境变量时如何使用?
部署应用程序后,本地
appsettings.json
值将在 Aure 应用程序设置中可用。
如果你想用Azure Web App中的设置覆盖本地
appsettings.json
文件的值,那么我们需要在应用程序设置中设置值。
您可以直接在门户中添加它,也可以在部署应用程序后从
Visual Studio
的托管部分进行添加。
我在这里添加 Visual Studio
Hosting
部分。
App settings
和 KUDU Console
中检查相同内容。Azure 应用设置:
库杜:
KUDU 控制台路径 -
https://YourAppName.scm.azurewebsites.net/Env.cshtml