我在使用 Net Core 3.1 的控制台应用程序中将用户机密与 Azure SDK WebJobs 结合使用时遇到问题
I am having trouble in using User Secrets with Azure SDK WebJobs in a console application using Net Core 3.1
我正在尝试使用用户机密,因为我想将我的密钥 AzureWebJobsStorage
保存在 secrets.json
中用于本地开发。
- 所以问题是:
我创建了我的用户机密,安装了必要的包,但是 我的网络作业仍在尝试使用我的 appsettings.json
.
中的密钥
到目前为止我完成了什么:
I can read my secrets.json但我不知道从这里到哪里去。
我尝试了什么
我搜索了 google,但找不到答案。我在 Whosebug 中看到了类似的问题,但它们指的是 NetCore 2.0 或其他对我没用的东西。
我的文件:
Program.cs
public class Program
{
static async Task Main()
{
var builder = new HostBuilder();
builder
.UseEnvironment("Development")
.ConfigureAppConfiguration((context, b) =>
{
if(context.HostingEnvironment.IsDevelopment())
b.AddUserSecrets<Program>();
})
.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddAzureStorage();
})
.ConfigureLogging((context, b) =>
{
b.AddConsole();
})
.ConfigureServices((context, b) =>
{
Infrastructure.IoC.DependencyResolver.RegisterServices(b, context.Configuration);
});
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
}
Functions.cs
public class Functions
{
private readonly ITransactionService _transactionService;
public Functions(ITransactionService transactionService)
{
_transactionService = transactionService;
}
public void ProcessQueueMessage([QueueTrigger("my_queue")] string message, ILogger logger)
{
try
{
Validate.IsTrue(long.TryParse(message, out long transactionId), "Invalid transaction from queue");
_transactionService.CategorizeAllOtherTransactions(transactionId).Wait();
}
catch (System.Exception)
{
logger.LogInformation(message);
}
}
}
.csproj 文件:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>7f046fd1-a48c-4aa6-95db-009313bcb42b</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.6" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="4.0.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.7" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Yaba.Infrastructure.IoC\Yaba.Infrastructure.IoC.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
你可以参考下面的代码来获取Configuration["MyOptions:Secret1"]
的secrets值。
public static IConfigurationRoot Configuration { get; set; }
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
builder.AddUserSecrets<Program>();
Configuration = builder.Build();
var a = Configuration["MyOptions:Secret1"];
}
public class MyOptions
{
public string Secret1 { get; set; }
public string Secret2 { get; set; }
}
secrets.json
如下所示:
{
"MyOptions": {
"Secret1": "123",
"Secret2": "456"
}
}
此外,您可以在 Main 中使用以下代码来获取机密值。
var services = new ServiceCollection()
.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)))
.BuildServiceProvider();
var options = services.GetRequiredService<IOptions<MyOptions>>();
var b = options.Value.Secret1;
正如我们在 GitHub 上讨论的那样,用户机密可用于解析 AzureWebJobsStorage
值。
关键要素:
Program.cs
builder.ConfigureAppConfiguration((context, configurationBuilder) =>
{
configurationBuilder
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: false)
.AddEnvironmentVariables();
if (context.HostingEnvironment.IsDevelopment())
{
configurationBuilder
.AddUserSecrets<Program>();
}
});
secrets.json:
{
"ConnectionStrings": {
"AzureWebJobsStorage": "..."
}
}
launch.json:
{
"profiles": {
"WebJob-netcore-sample": {
"commandName": "Project",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}
我正在尝试使用用户机密,因为我想将我的密钥 AzureWebJobsStorage
保存在 secrets.json
中用于本地开发。
- 所以问题是:
我创建了我的用户机密,安装了必要的包,但是 我的网络作业仍在尝试使用我的 appsettings.json
.
到目前为止我完成了什么:
I can read my secrets.json但我不知道从这里到哪里去。
我尝试了什么
我搜索了 google,但找不到答案。我在 Whosebug 中看到了类似的问题,但它们指的是 NetCore 2.0 或其他对我没用的东西。
我的文件:
Program.cs
public class Program
{
static async Task Main()
{
var builder = new HostBuilder();
builder
.UseEnvironment("Development")
.ConfigureAppConfiguration((context, b) =>
{
if(context.HostingEnvironment.IsDevelopment())
b.AddUserSecrets<Program>();
})
.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddAzureStorage();
})
.ConfigureLogging((context, b) =>
{
b.AddConsole();
})
.ConfigureServices((context, b) =>
{
Infrastructure.IoC.DependencyResolver.RegisterServices(b, context.Configuration);
});
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
}
Functions.cs
public class Functions
{
private readonly ITransactionService _transactionService;
public Functions(ITransactionService transactionService)
{
_transactionService = transactionService;
}
public void ProcessQueueMessage([QueueTrigger("my_queue")] string message, ILogger logger)
{
try
{
Validate.IsTrue(long.TryParse(message, out long transactionId), "Invalid transaction from queue");
_transactionService.CategorizeAllOtherTransactions(transactionId).Wait();
}
catch (System.Exception)
{
logger.LogInformation(message);
}
}
}
.csproj 文件:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>7f046fd1-a48c-4aa6-95db-009313bcb42b</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.6" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="4.0.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.7" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Yaba.Infrastructure.IoC\Yaba.Infrastructure.IoC.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
你可以参考下面的代码来获取Configuration["MyOptions:Secret1"]
的secrets值。
public static IConfigurationRoot Configuration { get; set; }
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
builder.AddUserSecrets<Program>();
Configuration = builder.Build();
var a = Configuration["MyOptions:Secret1"];
}
public class MyOptions
{
public string Secret1 { get; set; }
public string Secret2 { get; set; }
}
secrets.json
如下所示:
{
"MyOptions": {
"Secret1": "123",
"Secret2": "456"
}
}
此外,您可以在 Main 中使用以下代码来获取机密值。
var services = new ServiceCollection()
.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)))
.BuildServiceProvider();
var options = services.GetRequiredService<IOptions<MyOptions>>();
var b = options.Value.Secret1;
正如我们在 GitHub 上讨论的那样,用户机密可用于解析 AzureWebJobsStorage
值。
关键要素:
Program.cs
builder.ConfigureAppConfiguration((context, configurationBuilder) =>
{
configurationBuilder
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: false)
.AddEnvironmentVariables();
if (context.HostingEnvironment.IsDevelopment())
{
configurationBuilder
.AddUserSecrets<Program>();
}
});
secrets.json:
{
"ConnectionStrings": {
"AzureWebJobsStorage": "..."
}
}
launch.json:
{
"profiles": {
"WebJob-netcore-sample": {
"commandName": "Project",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}