Search code examples
c#json.net.net-5

.net5 secrets.json not being used locally


I have a .net5 web app in which I am trying to add a secrets.json file so I have right clicked and created the file - in my project file I can see:

<PropertyGroup>
  <TargetFramework>net5.0</TargetFramework>
  <UserSecretsId>1cb5a573-309c-4b03-b7e9-3c09794038bb</UserSecretsId>
</PropertyGroup>

The secrets.json file exists in AppData\Roaming\Microsoft\UserSecrets\1cb5a573-309c-4b03-b7e9-3c09794038bb:

{
  "GraphApi": {
    "ClientSecret": "secret-key"
  },
}

In my appsettings.json:

"GraphApi": {
  "TenantId": "tenant-id",
  "Scopes": ".default",
  "ClientId": "client-id",
  "ClientSecret": "From user secrets"
},

and in my program.cs:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .ConfigureAppConfiguration((hostContext, builder) =>
            {
                if (hostContext.HostingEnvironment.IsDevelopment())
                {
                    // Use user secrets for local development
                    builder.AddUserSecrets<Program>();
                }
            });

however, it's not picking up my ClientSecret from the secrets.json - if I put the value in appsettings.json, it works just fine - is there anything else I need to do to make it work?


Solution

  • Turns out there was a web.config that was added to the project and in that it wsa pointing the project to use the appsettings.development version which was overriding the secrets:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <location path="." inheritInChildApplications="false">
        <system.webServer>
          <handlers>
            <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
          </handlers>
          <aspNetCore processPath="bin\Debug\net5.0\Project.WebApp.exe" arguments="" stdoutLogEnabled="false" hostingModel="InProcess">
            <environmentVariables>
              <environmentVariable name="ASPNETCORE_HTTPS_PORT" value="443" />
              <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
            </environmentVariables>
          </aspNetCore>
        </system.webServer>
      </location>
    </configuration>
    

    Deleting this file and re-configuring the project to use iis express instead of iis fixed the issue