I know this is still in preview, but I just want to make sure I am not doing anything wrong as I have done things like this in the past. I have my Environment variables set in properties:
And I am trying to set up my tests:
[TestInitialize]
public void Initialize()
{
var test = Environment.GetEnvironmentVariables();
// test enumerates all the Env variables, don't see it there
var connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING");
if (string.IsNullOrWhiteSpace(connectionString)) // so this is obviously null
throw new ArgumentNullException("CONNECTION_STRING");
_ConnectionString = connectionString;
}
As you can see by my comments, the environment variables are not found/loaded.
What am I missing? Thank you.
I'm assuming that you are using Visual Studio 2022 because you are using .NET 6 and the minimal host (i.e., no Startup.cs)?
The general preference is not to store information in the Environment Variables given that this information is often uploaded to GitHub and can be trawled and used against you.
For a local development secret, the preference is to store these using the secrets.json file. There is information on how to do this at Safe Storage of Secrets, as well as details on accessing Configuration files at Accessing Configuration File Information.
For the TL;DR: Crowd the steps below might help (this is what I did in my Blazor app with .NET 6):
In Visual Studio 2022, right click on the project in question and select 'Manage User Secrets'. This will create a local secrets.json file and open it. It will also add a GUID in your project tile for UserSecretsId.
Create your secrets as JSON key value pairs in this file as you would for environment variables.
Go to 'Connected Services' in your project and configure the Secrets.json service.
Add the 'User Secrets' to your configuration file; this will depend on exactly where this is happening.
Inject the IConfiguration into your controller and save this to a field.
Call the data you want using:
{yourConfigurationFieldName}.GetValue<string>({yourJsonKey})
In Visual Studio 2022, you can access environment variables in development by modifying the following section of launchSettings.json file.
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"VaultUri": "https://xxx.vault.azure.net/",
"AZURE_USERNAME": "xxx#user.com"
}
where VaultUri is the name of your environment variable.
Related
I saw in this answer (link #1) that I can add my DB connection string in launchSettings.json instead of appsettings as an environment variable (for local development purposes).
Our appsettings.Development.json is reserved for publishing, deploying and testing our company's app in the Development environment, not for running the app in my local development environment (ie. Visual Studio). So our Development environment is actually a dev test environment.
How do I force the app to get the connection string Environment Variable from launchSettings.json (as show in the link #1) instead of appSettings.Development.json when running the app in my LOCAL development environment (i.e. via Visual Studio)? Question 1: Is there an IConfiguration method to do that forcing?
I am thinking I could do something in my code like:
string connectionString;
if (_configuration.forceGetFromLaunchSettings("ConnectionString") == null) {
connectionString = _config.GetValue<int>("AppSettings:ConnectionString"); // This will run in the Dev (test) environment
}
else {
connectionString = _configuration.forceGetFromLaunchSettings("ConnectionString"); // This will run in the local (Visual Studio) environment.
}
👆 So is there any pre-existing IConfiguration method like .forceGetFromLaunchSettings()
Question 2: If the above does not work or is too janky of a solution, do I need create a separate appsettings.Local.json file to hold my local appsettings? If yes, then how do I run the app in Visual Studio using that new appsetting file?
PS: If both of the above solutions are jank, please suggest a different one.
I'm following the docs for Configuration in .Net, and having trouble getting it working with User Secrets in Visual Studio 2022 (.Net 6.0).
Thus far I've:
Installed Microsoft.Extensions.Configuration.UserSecrets, and Microsoft.Extensions.Hosting.
Confirmed that <UserSecretsId> was added to the .csproj file
Code
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
// Retrieve App Secrets
using IHost host = Host.CreateDefaultBuilder(args).Build();
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();
string secret = config.GetValue<string>("DUMMY_VALUE");
...
await host.RunAsync();
secrets.json (Opened by right-clicking the project and choosing 'Manage User Secrets')
{
"DUMMY_VALUE": "dummy-test-value"
}
In the above, secret is null. Based on this line from the docs, I thought the code above would create a default config capable of reading the secrets.json file.
It seems like the way this works has been updated since similar questions were asked and answered, like this one. I've also been referencing the docs on Secrets in ASP applications, but still having trouble spotting what I'm missing.
With help from this answer and the docs for AddUserSecrets, I have a working solution: construct a custom config object with the desired capability.
code
using Microsoft.Extensions.Configuration;
// Retrieve App Secrets
IConfiguration config = new ConfigurationBuilder()
.AddUserSecrets<SomeClass>()
.Build();
string secret = config.GetValue<string>("DUMMY_VALUE");
...
Here, SomeClass can be any class in the assembly. The in-IDE description for AddUserSecrets<T> says:
AddUserSecrets will search the assembly that contains class T for some instance of Microsoft.Configuration.UserSecrets.UserSecretsIdAttribute which specifies the user secrets ID.
After following the steps listed in the question, this code succeeds in reading the secrets.json file. This solution is hinted at in the docs on Secrets in ASP.NET Core applications.
As mentioned by Bellrampion, the steps described in the Configuration in .Net docs will only read the secrets.json file in the Development configuration - which I do not see as an option in Visual Studio 2022. Based on this, if you want to use User Secret management in a .Net Console application in VS 2022, you may need to construct the custom config object like above.
In Vistual Studio 2022:
Select a project that will use the secrets;
Open context menu, select Manage User Secrets:
Library “Microsoft.Extensions.Configuration” will be auto added;
A secrets.json file will be auto created: fill it with access token, etc.
{
"github": {
"accessToken": "xx"
}
}
use the following lines to fetch a secret in a class, e.g. Program.cs
using Microsoft.Extensions.Configuration;
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
IConfiguration configuration = configurationBuilder.AddUserSecrets<Program>().Build();
string githubToken = configuration.GetSection("github")["accessToken"];
I'm trying to set up a very simple test application for connecting to my Firebase Cloud Firestore instance.
It's a C# .NET Core console application using .NET Core 3.0 on Windows 7
I'm just trying to connecting to my Firestore instance using my project name.
My GOOGLE_APPLICATION_CREDENTIALS environment variable is set to C:\test\creds.json which I created from using the "Create Key" feature on the GCP Console page for my default service account.
When I run the code below, I get the following error:
using Google.Cloud.Firestore;
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
FirestoreDb db = FirestoreDb.Create("my-proj-id");
}
}
}
Exception:
The Application Default Credentials are not available. They are
available if running in Google Compute Engine. Otherwise, the
environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined
pointing to a file defining the credentials. See
https://developers.google.com/accounts/docs/application-default-credentials
for more information.'
When I run ProcessMonitor to detect file system activity, my application never even tries to touch the creds.json file, which makes me believe the C# Cloud Firestore API isn't even finding my creds file. I've set the GOOGLE_APPLICATION_CREDENTIALS env variable at both the user and system level.
Is there a problem with how I've configured things?
Well this was maddening. I tried to log the GOOGLE_APPLICATION_CREDENTIALS environment variable value in my app and it was null. I restarted Visual Studio and it started to work. My theories are that either VS passed the current environment to the debugee when it launches the debugger process or that it may use one of those Visual Studio debugger host proxy processes for debugging and it was restarted after I restarted the IDE
Sometimes the environment that Visual Studio is running can be different to the scope of the PATH ENV variables in Windows. I think it is related to the Admin permission. It would be interesting to execute the task and the GOOGLE_APPLICATION_CREDENTIALS assignment opening Visual Studio as Administrator.
Seems that this behavior is expected. C# .net MVC, set path to Google Application Credentials JSON file
I am trying to get access to some docker environment variables in my C# code running on .Net Core.
In my dockerfile generated by VS, I added environment variables like this:
ENV EnvKey = "value"
After building this image and starting the instance with the built-in Docker startup option in VS, I inspect my docker image with docker inspect MyInstance.
The resulting output lists my previously defined environment variable in "Config" -> "Env" -> "EnvKey", so I'm sure it is there.
For some testing, I try to access them with the following code:
var keys = Environment.GetEnvironmentVariables();
However, this does not retrieve the environment variable that is contained in the container.
What else do I need to configure to get this working?
The problem was very simple actually - In my case, this wasn't visible from the question.
But my real environment variable key had some "." in it. I replaced those with "_" and now it works perfectly.
If you are running an ASP.NET application, then updating the Dockerfile to ENV ASPNETCORE_EnvKey = "value" should do the trick for you.
If you are running some other .NET core app on your machine, then look at the docs here. It would seem you can't do this on the machine level, but in your RUN command, you would have to pass the 'environment variables' to the process through the dotnet command you are invoking there.
Using ef core it's possible to get everything working and run the dotnet ef migrations command line tool but Program.cs required the method
public static IHostBuilder CreateHostBuilder(string[] args)
The only thing that isn't ideal is storing database settings in a development json file then having to hardcode the development json file name in that method or hardcoding the db connection details into that method. When checking
context.HostingEnvironment.IsDevelopment() //always returns false
it is never correct or doesn't get set properly so we can't use context.HostingEnvironment.EnvironmentName as a variable either. Is there a way in the CreateHostBuilder method to load the proper app settings json file and configure/setup the environment for running the ef migrations command line tools vs hardcoding?
Yes, you have a few options to setup the Hosting Environment.
You can set a value of the DOTNET_ENVIRONMENT environment variable. This applies to all types of apps. Or you can setup ASPNETCORE_ENVIRONMENT environment variable, as this overrides the DOTNET_ENVIRONMENT when .ConfigureWebHostDefaults is called.
Another options is to set the ASPNETCORE_ENVIRONMENT value in the launchSetting.json of your project.
While you can give any value to those environment variables, the framework provides the following values: "Development", "Staging", and "Production".
You can find more information about this in the Use Multiple Environments in ASP.NET Core docs.