As we are still using SQL accounts to connect to our databases locally, I wanted to avoid accidently checking in the SQL account information. So instead of storing my connectionstring directly in the appsettings.json file I wanted to use the secrets.json file instead. Let us find out how to achieve this...
When storing your connectionstring inside your appsettings.json you can use the GetConnectionString()
method to fetch a connectionstring:
The same technique also works when using the built-in secret manager tool and the corresponding secrets.json. By default user secrets are loaded when your environmentname is set to Development
. You can explicitly enable this by adding the following code:
User Secrets are stored in a separate secrets.json. You can edit the secrets using the Secret Manager tool (dotnet user-secrets) or directly in Visual Studio by right clicking on the web project and choosing ‘Manage User Secrets’:
Remark: You can find the secrets.json file here at %APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json
The information in the appsettings.json and secrets.json will be merged. The connectionstring should be added to the secrets.json file using the following format(similar to the appsettings.json):