簡體   English   中英

我在使用 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

我想使用的用戶秘密,因為我要救我的鑰匙AzureWebJobsStoragesecrets.json地方發展。

  • 所以問題是:

我創建了我的用戶機密,安裝了必要的包,但我的 webjob 仍在嘗試使用我的appsettings.json的密鑰

到目前為止我取得的成就:

我可以閱讀我的 secrets.json但我不知道從哪里開始。

我試過什么

我已經通過谷歌搜索,但無法找到答案。 我在 StackOverflow 中看到了類似的問題,但它們指的是 NetCore 2.0 或其他對我沒有用的東西。

我的文件:

程序.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();
        }
    }
}

函數.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"]獲取機密值。

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值。

關鍵要素:

程序.cs

            builder.ConfigureAppConfiguration((context, configurationBuilder) =>
            {
                configurationBuilder
                    .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: false)
                    .AddEnvironmentVariables();

                if (context.HostingEnvironment.IsDevelopment())
                {
                    configurationBuilder
                        .AddUserSecrets<Program>();
                }
            });

秘密.json:

{
  "ConnectionStrings": {
    "AzureWebJobsStorage": "..."
  }
}

啟動.json:

{
  "profiles": {
    "WebJob-netcore-sample": {
      "commandName": "Project",
      "environmentVariables": {
        "DOTNET_ENVIRONMENT": "Development"
      }
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM