How to get "Manage User Secrets" in a .NET Core console-application?
.Net Coreasp.net Core-1.0Visual Studio-2017.Net Core Problem Overview
When I create a new ASP .NET Core Web-Application, I can right-click the project in Visual Studio, and I see a context-menu entry called "Manage User Secrets".
When I create a new .NET Core Console-Application, I don't see this context-menu entry.
However, a "Web"-Application shows as "console" application in the project settings. Is there any way I can get this context-menu entry in a console-application ?
.Net Core Solutions
Solution 1 - .Net Core
"Manage user secrets" from a right click is only available in web projects.
There is a slightly different process for console applications
It requires manually typing the required elements into your csproj file then adding secrets through the PMC
I have outlined the process that worked for me in my current project step by step in this blog post :
tl;dr
Step 1
Right click project and hit edit projectName.csproj
Step 2
add <UserSecretsId>Insert New Guid Here</UserSecretsId>
into csproj under TargetFramework
add <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0"/>
within Item Group in csproj
Step 3
Open PowerShell (admin) cd into project directory and
enter dotnet user-secrets set YourSecretName "YourSecretContent"
This will create a secrets.json file in:
%APPDATA%\microsoft\UserSecrets\<userSecretsId>\secrets.json
Where userSecretsId = the new Guid you created for your csproj
Step 4
Open secrets.json and edit to look similar to this
{
"YourClassName":{
"Secret1":"Secret1 Content",
"Secret2":"Secret2 Content"
}
}
By adding the name of your class you can then bind your secrets to an object to be used.
Create a basic POCO with the same name that you just used in your JSON.
namespace YourNamespace
{
public class YourClassName
{
public string Secret1 { get; set; }
public string Secret2 { get; set; }
}
}
Step 5
Add Microsoft.Extensions.Configuration.UserSecrets
Nuget package to project
Add
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddUserSecrets<YourClassName>()
.AddEnvironmentVariables();
&
var services = new ServiceCollection()
.Configure<YourClassName>(Configuration.GetSection(nameof(YourClassName)))
.AddOptions()
.BuildServiceProvider();
services.GetService<SecretConsumer>();
To your Program.cs file.
Then inject IOptions<YourClassName>
into the constructor of your class
private readonly YourClassName _secrets;
public SecretConsumer(IOptions<YourClassName> secrets)
{
_secrets = secrets.Value;
}
Then access secrets by using _secrets.Secret1;
Thanks to Patric for pointing out that services.GetService<NameOfClass>();
should be services.GetService<SecretConsumer>();
Solution 2 - .Net Core
Manage User Secrets
is available from the context menu of .NET Core Console projects (not just ASP.NET Core projects) since Visual Studio 2019 (verified in version 16.1.3), once you reference the Microsoft.Extensions.Configuration.UserSecrets
NuGet.
Solution 3 - .Net Core
Dotnet Core 3.1 - simplest method I have found in situations when I just need to hide a password.
Create user secrets using command line from project folder
dotnet user-secrets init
dotnet user-secrets set mailpassword password1
in Program.cs
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
var secretProvider = config.Providers.First();
secretProvider.TryGet("mailpassword", out var secretPass);
//'secretPass' should now contain the password
//if the "mailpassword" secret is not found, then 'secretPass' will be null
If you are doing more things with configuration you may need to adjust the .First()
Solution 4 - .Net Core
1.Add to your project file (Prior to dotnet 2.1 only):
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
</ItemGroup>
2.Set
<PropertyGroup>
<UserSecretsId>a random user id: manually add</UserSecretsId>
</PropertyGroup>
3. Move to the migration project folder in Package Manager Console and add a key:value like:
dotnet user-secrets set "ConnectionStrings:DefaultConnection" "xxxxx"
Remember to be in the directory of that project (for Package manager console this means cd'ing into the project, not solution level)
Solution 5 - .Net Core
- Right click on the project and click edit csproj file.
- On first line replace
<Project Sdk="Microsoft.NET.Sdk">
with<Project Sdk="Microsoft.NET.Sdk.Web">
and save.
Now you can access to manage user secrets menu, edit it and save. Then you have to restore the first line of the csproj file to its defaults to be again a console app.
It's stupid but it works. Remember replace the usersecretsid property for every project or will just have one secrets.json
for all your projects.
Solution 6 - .Net Core
It appears that they haven't added that (at least to Visual Studio 2015) as an option for Console or DLL apps.
You can use this as a work around, but do so at your own risk, it will trick Visual Studio into believing that the dll project has Web capabilities as well.
Assuming Windows OS
-
Open File Explorer to
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v{Version Number}\DotNet
note: 14.0 is VS 2015, 15.0 is 2017 etc -
backup the file named
Microsoft.DotNet.targets
-
Add this line to
Microsoft.DotNet.targets
next to the otherProjectCabability
tag<ProjectCapability Include="DotNetCoreWeb" />
-
Save the file, and unload and reload your project / restart visual studio.
You may also need to delete your .suo file and/or your .vs folder
You should now see the context menu. It also changes the icon unfortunately. It seems to build just fine, but this is pretty untested so seriously, use at your own risk.
Solution 7 - .Net Core
There is already an open closed issue related to this on GitHub.
What you can do until they solve it, is to use the command line approach as described on Visual Studio Code or Command Line: Installing the Secret Manager tool. This doesn't mean that you get your context menu item but it works nevertheless.
One note, the documentation is referring to <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.1" />
while version 2.0.0
is already out and can be used.
Solution 8 - .Net Core
Additionally to the answers posted here, if you want a link to your own secrets.json file in your project, you can add the following code to an ItemGroup in your project file:
<None Include="$(AppData)\microsoft\UserSecrets\$(UserSecretsId)\secrets.json" Link="secrets.json" />
Solution 9 - .Net Core
As of 2022, this context menu entry is available for both web (Microsoft.NET.Sdk.Web
) and non-web (Microsoft.NET.Sdk
) projects, but only if you also have the "ASP.NET and web development" workload installed (you can untick all optional features during setup if you don't need them).
So once you add it via "Tools > Get Tools and Features..." it'll appear on both kinds of projects.
Typically happens to me on a fresh install not requiring to develop web projects by default, but using user secrets in console apps aswell.
Solution 10 - .Net Core
If it's only needed get the User Secrets configuration, it's enough on the constructor of YourSecretClass
the follow code:
public YourSecretClass()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddUserSecrets<Secrets>().Build();
SecretID = builder.GetSection("SecretID").Value;
SecretPwd = builder.GetSection("SecretPwd").Value;
}
Solution 11 - .Net Core
How to get “Manage User Secrets” in a .NET Core console-application?
Using Visual Studio 2015 Community with update 3
- File -> New-> Project
- Select Console Application (.NET Core)
- Press CTRL+ALT+L
- Click on the project to get “Manage User Secrets” it will open up a file called secrets.json
and where you can manually enter user-secrets.
I was able to use command prompt to setup user secrets:
c:\Projects\ConsoleApp2\src\ConsoleApp2>dotnet user-secrets set BrainTree_sandbox:Merchant ID:9rv9mhnb5gh7nnyx