I have set up a .net core application on linux using nginx. It works perfectly with dotnet MyProject.dll
. However, using the instructions in this link, when I try setting up a kestrel service, it doesn’t seem to be able to use the Configuration
in the startup class. Here is my Program
public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) { var configEnv = new ConfigurationBuilder().AddEnvironmentVariables().Build(); return WebHost.CreateDefaultBuilder(args) .UseKestrel() .ConfigureAppConfiguration((ctx, builder) => { var keyVaultEndpoint = configEnv["KEYVAULT_ENDPOINT"]; if (!string.IsNullOrEmpty(keyVaultEndpoint)) { var azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback( azureServiceTokenProvider.KeyVaultTokenCallback)); builder.AddAzureKeyVault( keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager()); } }) .UseStartup<Startup>() .UseUrls("http://localhost:5050") .Build(); } }
My start up class has the following:
services.AddDbContext<ApplicationDBContext>(config => { config.UseMySql(Configuration["ConnectionString"]); });
I keep getting an error saying that the connectionString
parameter attribute can’t be null when I run it with kestrel. The connection string is set up in azure key vault. This and all other secrets work when I do dotnet MyProject.dll
. When using the kestrel service, I have also tried setting the environment variable, it still doesn’t shows the same error.
This is my kestrel service:
[Unit] Description=Example.NET Web API App running on Ubuntu [Service] WorkingDirectory =/ home / MyProject / publish2 / files ExecStart=/usr/bin/dotnet /home/MyProject/publish2/files/MyProject.dll Restart = always RestartSec=10 # Restart service after 10 seconds if dotnet service crashes SyslogIdentifier=dotnet-example User = www - data #Environment=ASPNETCORE_ENVIRONMENT=Production #Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false/etc/systemd/system/ [Install] WantedBy=multi-user.target
I had tried with and without commenting the environment variables above. same result. Is there something I have to add for my kestrel service?
Update
Even tried setting Environment=ConnectionString
in the service file, still the same.
Advertisement
Answer
It turns out the only environment variables the .net core
reads when ran using a service are the variables configured within the service file. Adding it in this file resolved the issue:
Environment=KEYVAULT_ENDPOINT=myendpointurlhere