ASP.NET Load user secrets.json when environment is not Development

problem

In an ASP.NET project on .NET 6 the user secrets are only loaded when the environment used is Development.

From https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-6.0&tabs=windows:

"WebApplication.CreateBuilder initializes a new instance of the WebApplicationBuilder class with preconfigured defaults. The initialized WebApplicationBuilder (builder) provides default configuration and calls AddUserSecrets when the EnvironmentName is Development."

Sometimes you need to run the project locally using a different environment, like Production, or anything different from Development. By default, the user secrets are not loaded in this situation. What should you do to load them?

solution

You can explicitly build the configuration again, including the appsettings file for your environment, before the code that needs the values from it, and call the AddUserSecrets method. This is how the code would look like for the Production environment:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddJsonFile("appsettings.Production.json")
    .AddUserSecrets(Assembly.GetExecutingAssembly())
    .Build();

var azureKey = configuration["AzureKey"];
Gravatar
Author: Dan Dumitru
Last Edit: July 27, 2022
Last Edit July 27, 2022
Created July 27, 2022
Views 133
Tags
ASP.NET
C#

Join us!

Do you like this website?

Bookmark it and come back here to write a post yourself when you run into something shareable.

Early collaborators will get to own a part of the project (5 to 20%)... >> read more

Your Comment

Feel free to post additional info or improvement suggestions.
preview
Optional, never shown, displays gravatar.

Formatting Tips

This editor uses Markdown to easily add code in your posts.

Triple backticks for full line(s) of code (or indent 4 spaces)

```
let foo = 'bar';
```

[link text](http://a.com)

*italic* **bold**

More Tips