Forum Discussion
Can I access User Secrets from a _Framework_ Web API project?
I'm targeting .NET Framework 4.8, mainly because I sometimes have to interact with Access databases and I assume I have a better chance of that working for framework than .NET Core.
When deployed, I want this API to pick up any credentials it needs from environment variables but I would like to be able to test it locally, so I'm trying to find the best place to store the credentials without checking them in.
I have read this and similar articles - user secrets seems like a reasonable solution, maybe there are better ones.
https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-8.0&tabs=windows&source=docs
The part about "Manage User Secrets" in Visual Studio seemed to work at least partially: it installed Microsoft.Configuration.ConfigurationBuilders.UserSecrets and added this to my Web.config:
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" />
</configSections>
<configBuilders>
<builders>
<add name="Secrets" userSecretsId="583724f7-d984-4688-84cd-cb8b28df5527" type="Microsoft.Configuration.ConfigurationBuilders.UserSecretsConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.UserSecrets, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</builders>
</configBuilders>
It loaded up a secrets.xml file and I can find examples of adding secrets to that.
Where I'm stuck is how to access them from the code. I see .NET Core examples where they call AddUserSecrets<Program>() on their ConfigurationBuilder in their Config.cs but again mine is a framework app and I just have a WebApiConfig.cs with a Register(HttpConfiguration config).
In there it accesses GlobalConfiguration.
I just don't have the past experience to figure out what the analogous thing would be for framework.
Thanks,
-Jeff
2 Replies
- J_JeffRobertsCopper ContributorWith this setup should the secrets in the secrets.xml file end up in ConfigurationManager.AppSettings[]?
For me they do not, I only see the 4 settings in my Web.config/configuration/appSettings element.- J_JeffRobertsCopper Contributor
This was answered elsewhere - I just needed to add this attribute to the appSettings element in my Web.config:
<appSettings configBuilders="Secrets">