I am pulling my hair out right about now. I have tried getting the Secrets multiple different ways. Here is where I am at:
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(); });
}
}
When I check via the CLI I can see that the secret(s) are set correctly
dotnet user-secrets list
MyPassword = *************
What am I missing?
Service Fabric, when run local, is run within a Docker Container. This means that the folder the Secrets.json file is located on natively is inaccessible to anything running in the container. For the short term (hack) I moved the secrets.json to my app root folder (with appsettings.json) and marked it in my .gitignore so it is not checked in. I also added it to the above configuration code. Works fine but the default Configuration will never find it there so i am keeping my hand rolled configuration builder.