0

我现在正在拔头发。我尝试过以多种不同的方式获取秘密。这是我所在的位置:

public class Startup
{
    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
        //Configuration = configuration;  // <<=== THIS DOES NOT WORK - CONFIG IS ALWAYS EMPTY ===

        // Manually add configuration...
        var app = Assembly.Load(new AssemblyName(env.ApplicationName));
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) // When app is published
            .AddEnvironmentVariables();

        if (app != null && env.IsDevelopment())
            builder.AddUserSecrets(app, optional: false);

        Configuration = builder.Build();
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        var connectionString = Configuration.GetConnectionString("MySqlConn");
        var password = Configuration["MyPassword"];  // <<===  THIS FAILS - ALWAYS NULL ===
        var builder = new SqlConnectionStringBuilder(connectionString);
        builder.Password = password;
        connectionString = builder.ConnectionString;

        services.AddDbContext<MySqlContext>(options => options.UseSqlServer(connectionString));
        services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1"); c.RoutePrefix = string.Empty; });

        if (!env.IsProduction())
            app.UseDeveloperExceptionPage();

        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    }
}

当我通过 CLI 检查时,我可以看到密码设置正确

dotnet 用户机密列表
MyPassword = *************

我错过了什么?

4

1 回答 1

0

Service Fabric 在本地运行时,在 Docker 容器中运行。这意味着 Secrets.json 文件本机所在的文件夹对于容器中运行的任何内容都无法访问。对于短期(黑客),我将 secrets.json 移动到我的应用程序根文件夹(使用 appsettings.json)并在我的 .gitignore 中对其进行了标记,因此它不会被签入。我还将它添加到上述配置代码中。工作正常,但默认配置永远不会在那里找到它,所以我保留了我的手卷配置生成器。

于 2020-11-29T23:01:58.603 回答