简体   繁体   English

.Net 控制台应用程序中的用户机密问题

[英]Problems with user secrets in .Net console apps

I've created a.Net 6 console app.我创建了一个.Net 6 控制台应用程序。 I added user secrets, but I only get the values defined in the appsettings.json file.我添加了用户机密,但我只获得了 appsettings.json 文件中定义的值。 I use Visual Studio Professional 2022 version 17.0.4.我使用 Visual Studio Professional 2022 版本 17.0.4。

Initial steps初始步骤

  1. Create a new.Net 6 console app from Visual Studio 2022's project templates.从 Visual Studio 2022 的项目模板创建一个新的 .Net 6 控制台应用程序。
  2. Install the Microsoft.Extensions.Hosting nuget package (version 6.0.0).安装 Microsoft.Extensions.Hosting nuget package(版本 6.0.0)。
  3. Install the Microsoft.Extensions.Configuration.UserSecrets nuget package (version 6.0.0).安装 Microsoft.Extensions.Configuration.UserSecrets nuget package(版本 6.0.0)。
  4. Add the appsettings.json file and set Copy to Output Directory to Copy always.添加 appsettings.json 文件并将复制到 Output 目录设置为始终复制。
  5. Right-click on the project and select Manage User Secrets.右键单击项目和 select 管理用户机密。

Code代码

Program.cs程序.cs

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var host = Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) => 
                {
                    services.Configure<GlobalSettings>(context.Configuration.GetSection("GlobalSettings"));
                    services.AddTransient<Worker>();
                })
                .Build();

var work = host.Services.GetRequiredService<Worker>();
await work.ExecuteAsync();

Worker.cs工人.cs

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

public class Worker
{
    private readonly ILogger<Worker> _logger;
    private readonly GlobalSettings _globalSettings;

    public Worker(ILogger<Worker> logger, IOptions<GlobalSettings> globalSettings)
    {
        _logger = logger;
        _globalSettings = globalSettings.Value;
    }

    public async Task ExecuteAsync()
    {
        _logger.LogInformation(_globalSettings.Foo);
        _logger.LogInformation(_globalSettings.Bar);
        await Task.CompletedTask;
    }
}

GlobalSettings.cs:全局设置.cs:

public class GlobalSettings
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

.csproj: .csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>disable</Nullable>
    <UserSecretsId>deedd476-f5d6-47f4-982e-1645c89789c7</UserSecretsId>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>

appsettings.json: appsettings.json:

{
    "GlobalSettings": {
        "Foo": "Normal Foo",
        "Bar": "Normal Bar"
    }
}

secrets.json:秘密.json:

{
    "GlobalSettings": {
        "Foo": "Secret Foo",
        "Bar": "Secret Bar"
    }
}

What I've tried我试过的

  • Checked whether the user secret id in csproj matched the folder, which it did: C:\Users\Dennis\AppData\Roaming\Microsoft\UserSecrets\deedd476-f5d6-47f4-982e-1645c89789c7检查 csproj 中的用户密码 ID 是否与文件夹匹配,它确实:C:\Users\Dennis\AppData\Roaming\Microsoft\UserSecrets\deedd476-f5d6-47f4-982e-1645c89789c7
  • Rebuilded the project.重建了项目。
  • Closed Visual Studio 2022 and ran it again as administrator.关闭 Visual Studio 2022 并以管理员身份再次运行。
  • Created a new project from scratch.从头开始创建一个新项目。
  • Compared the code with one of my colleague's projects.将代码与我同事的一个项目进行了比较。 I couldn't find any difference, but his code works when I run it.我找不到任何区别,但他的代码在我运行时有效。
  • Changed IOptionsSnapshot to IOptions and IOptionsMonitor.将 IOptionsSnapshot 更改为 IOptions 和 IOptionsMonitor。
  • Changed AddTransient to AddSingleton.将 AddTransient 更改为 AddSingleton。
  • Did the same steps, but with a.Net 5 project instead.做了相同的步骤,但使用了一个 .Net 5 项目。

Thanks.谢谢。

I'd misunderstood the way the Host.CreateDefaultBuilder method worked.我误解了 Host.CreateDefaultBuilder 方法的工作方式。 According to the documentation ( docs ):根据文档( docs ):

load app IConfiguration from User Secrets when EnvironmentName is 'Development' using the entry assembly当 EnvironmentName 为“开发”时,使用入口程序集从用户机密加载应用程序 IConfiguration

My environment is Production (probably a fallback value).我的环境是生产环境(可能是后备值)。 It worked in my colleague's project because it included a launchSettings.json file with the DOTNET_ENVIRONMENT environment variable set to Development.它在我同事的项目中有效,因为它包含一个launchSettings.json 文件,其中 DOTNET_ENVIRONMENT 环境变量设置为 Development。

Remembered to call AssUserSecrets(...) in the Builder?记得在 Builder 中调用 AssUserSecrets(...) 吗?

https://makolyte.com/how-to-add-user-secrets-in-a-dotnetcore-console-app/ https://makolyte.com/how-to-add-user-secrets-in-a-dotnetcore-console-app/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM