runtime: usersecrets are not accessible inside container for worker service project

Describe the bug

The user secrets for a worker service are not accessible inside docker container.

To Reproduce

Steps to reproduce the behavior:

  1. Create a new .NET Core 3.0/3.1 WorkerService project using Visual Studio. (Or just clone this repo and jump to step 5)
  2. Right click on the project, click “Add Docker Support” select “Linux”.
  3. Edit the project file and add - a. Package reference to Microsoft.Extensions.Configuration.UserSecrets as following <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="3.1.1" /> Because of this issue #2743 b. A volume mapping of the user secrets directory inside the container by adding following line to the property group - <DockerfileRunArguments>-v "$(AppData)/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro"</DockerfileRunArguments>
  4. Modify the file Worker.cs to access the user secrets -
 public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private readonly IConfiguration configuration;

        public Worker(ILogger<Worker> logger, IConfiguration configuration)
        {
            _logger = logger;
            this.configuration = configuration;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("The secret - {}", this.configuration["secretKey"]);
                await Task.Delay(1000, stoppingToken);
            }
        }
    }
  1. On powershell or command prompt, navigate to the project directory and add user secrets using the command - dotnet user-secrets set "secretKey" "secretValue"

  2. hit F5 with the Docker debug profile and monitor the output window. Notice that the value of the user secret is null.

Note: You can open the Containers window in the VS to check the file contents of the container. If you check the path - /root/.microsoft/usersecrets you will notice the user-secrets directory with secrets.json inside it.

Expected behavior

The output should print the value of the user-secret.

Screenshots

Filesystem and output of the program

UserSecretIDAttribute in the assembly

Additional context

Same program with WorkerService debug profile works well.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 4
  • Comments: 15 (7 by maintainers)

Most upvoted comments

There’s no issue with the mount. The docker image default DOTNET_ENVIRONMENT value is * (it’s actually unset). If you set it to Development in the launchSettings.json, it will work.

    "Docker": {
      "commandName": "Docker",
      "environmentVariables": {
        "DOTNET_ENVIRONMENT": "Development"
      }
    }