我现在正在拔头发。我尝试过以多种不同的方式获取秘密。这是我所在的位置:
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 = *************
我错过了什么?