Reputation: 675
My question is simple. I have an ASP.net core 3.0 app, I added secrets using visualstudio and pasted my secrets into the secret file normally. Then inside my Program.cs, I added a call to addusersecrets as follows:
...
...
.AddUserSecrets<Startup>()
But while calling my secrets like Configuration["Authentication:Secret"]
as I used to do when it was in appsettings.json, I get a null value in return.
I went through stackoverflow and tried solutions like changing my addsecrets as follows:
.AddUserSecrets("fds...-...-...askd")
//OR
.AddUserSecrets(typeof(Startup).Assembly, true, reloadOnChange: true)
BUt none of then works.
I wonder if this secret stuff even works on asp.net core, because I don't see any reason my code doesn't work. please if someone gets it, can you tell me a solution ? Thanks.
Upvotes: 7
Views: 12041
Reputation: 557
In Asp.Net MVC 5, add this to Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, configuration) =>
{
configuration.Sources.Clear();
configuration.AddEnvironmentVariables();
configuration.AddUserSecrets(Assembly.GetExecutingAssembly(), true, true);
})
.UseSystemd()
.UseSerilog((context, service, configuration) => {
configuration
.MinimumLevel.Warning()
.Enrich.FromLogContext()
.WriteTo.Console();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Upvotes: 1
Reputation: 31576
For .Net 6 that doesn't use Startup
one loads the assembly such as
build.AddUserSecrets(Assembly.GetExecutingAssembly())
Upvotes: 2
Reputation: 319
User secrets are stored now in csproj project file. This is how you can read it(see image). I am using asp.net core 5
Upvotes: -2
Reputation: 51
Be sure to check that you've set the "ASPNETCORE_ENVIRONMENT"
variable to "Development"
, else your app wont add your user secrets.
in powershell:
$Env:ASPNETCORE_ENVIRONMENT = "Development"
cmd:
setx ASPNETCORE_ENVIRONMENT "Development"
Upvotes: 5
Reputation: 20082
Did your code look like this ?
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json",
optional: false,
reloadOnChange: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
builder.AddUserSecrets<Startup>();
}
Configuration = builder.Build();
}
Upvotes: 4