gpt4 book ai didi

c# - .net core Worker Service(BackgroundService)无法加载用户 secret

转载 作者:行者123 更新时间:2023-12-05 08:37:52 36 4
gpt4 key购买 nike

拥有 .net core 版本 3.1.8 和 asp.net core 版本 3.1.8 的 .net core worker 服务 我在从 worker 服务加载用户 secret 时遇到问题,但是在 asp.net core 项目中同样有效。

从 asp.net core 和 .net core worker 服务调用的通用方法

public static string GetFioApiKey(this IConfiguration configuration)
=> configuration["PaymentServiceSecrets:FioApiKey"];

worker服务的csproj

<Project Sdk="Microsoft.NET.Sdk.Worker">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>8d19c97d-a2fb-4a51-a694-9635b9c0c42c</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.8" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="3.1.8" />
</ItemGroup>
</Project>

worker服务的startup.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config => config.AddUserSecrets(Assembly.GetExecutingAssembly()))
.ConfigureServices((hostContext, services) =>
{
// simplified


services.AddSingleton<IApplicationSettings>(applicationSettings =>
{
var appSettings = new ApplicationSettings
{
FioApiKey = config.GetFioApiKey()
};


return appSettings;
});

services.AddHostedService<Worker>();
});
}

找到这个 link对于 github 问题,尝试应用解决方法但仍然无效

最佳答案

这里没有提到的一个“陷阱”是要求,在 WorkerServices 中,环境变量“DOTNET_ENVIRONMENT”必须设置为“Development”,否则 User Secrets 甚至不会尝试加载。这与 ASP.Net 项目中使用的“ASPNETCORE_ENVIRONMENT”环境变量形成对比。

即在 Properties/launchSettings.json 中

{
// .. Ommitted
"profiles": {
"MyWorkerService": {
"commandName": "Project",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}

通常,新的项目模板为您准备好了这个,但在我的例子中,当将 ASP.Net 项目(不需要 Web 服务器功能)转换为 Worker Services 时,launchSettings.json 配置文件设置“ASPNETCORE_ENVIRONMENT "到 "Development",这在 WorkerServices 中实际上是无用的。

关于c# - .net core Worker Service(BackgroundService)无法加载用户 secret ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64252988/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com