crgolden
crgolden

Reputation: 4614

ASP.NET Core app with "user-secrets" fails on macOS command line only

I'm using dotnet-user-secrets with an ASP.NET Core 2.1.4 app.

To be clear, this question is about invoking dotnet run from the command line in macOS; this issue does not exist when invoking dotnet run for the same application in Windows. Additionally, running the app from within Visual Studio works as expected on both macOS and Windows.

Typing dotnet user-secrets list at the command line returns the expected output:

TokenProviderOptions:SecretKey = …
TokenProviderOptions:Issuer = …
TokenProviderOptions:Audience = …

I can also access the secrets.json file in the ~/.microsoft/usersecrets/<userSecretsId> folder as expected:

{
  "TokenProviderOptions": {
    "SecretKey": "…",
    "Issuer": "…",
    "Audience": "…"
  }
}

Here is how I am accessing the secrets inside Startup.cs:

// Configure tokens
var tokenOptions = Configuration
    .GetSection("TokenProviderOptions")
    .GetChildren()
    .ToList();
string
    secretKey = tokenOptions.Single(x => x.Key.Equals("SecretKey")).Value,
    issuer = tokenOptions.Single(x => x.Key.Equals("Issuer")).Value,
    audience = tokenOptions.Single(x => x.Key.Equals("Audience")).Value;

As I mentioned before, this runs with no problems from Command Prompt and Visual Studio in Windows. And, from Visual Studio in macOS, I can debug and see the tokenOptions list with the three items. However, when I type dotnet run in Terminal, I get this error at the first .Single():

System.InvalidOperationException: Sequence contains no matching element

Is there an extra step I'm missing to run this successfully from the command line in macOS?

Upvotes: 1

Views: 3106

Answers (1)

Neville Nazerane
Neville Nazerane

Reputation: 7019

The secret manager is designed to only work on development. So, it only works as far as your ASPNETCORE_ENVIRONMENT is set to Development. This can be done in your environment variables.

If you do not wish to modify your environment variables, you can use the following in your program.cs file:

public static IWebHost BuildWebHost(string[] args)
{

    var config = new ConfigurationBuilder().AddUserSecrets("myid").Build();

    return WebHost.CreateDefaultBuilder(args)
            .UseConfiguration(config)
            .UseStartup<Startup>()

Upvotes: 5

Related Questions