Was trying to follow a tutorial here for a console app https://www.connectionstrings.com/store-and-read-connection-string-in-appsettings-json/
So in my appsettings-json i have:
{
"ConnectionStrings": {
"myDb1": "Server=myServer;Database=myDb1;Trusted_Connection=True;",
}
}
My program:
using System;
using Microsoft.Extensions.Configuration;
namespace mynamespace
{
class Program
{
string myDb1ConnectionString = _configuration.GetConnectionString("myDb1");
static void Main(string[] args)
{
...
}
}
}
The error I get is : "The name '_configuration' does not exist in the current context".
The page you link to isn't a tutorial, it only shows how to read a connection string from any configuration provider, not just appsettings.json. It assumes you've already built a configuration object. .NET (Core) 5 and 6 use far simpler code though.
Check Configuration in .NET to understand how configuration really works. You can find more detailed information on the various config providers, how they're used and how to create your own in Configuration in ASP.NET Core
Using a generic host
In .NET 6, the current long term version, a minimal application would need:
using Microsoft.Extensions.Hosting;
using IHost host = Host.CreateDefaultBuilder(args).Build();
var configuration=host.Services.GetRequiredService<IConfiguration>();
var connectionString=configuration.GetConnectionString("blahblah");
...
As the docs explain, CreateDefaultBuilder will load configuration settings from any appsettings.json files, environment variables and finally command-line parameters.
This means you can override the settings stored in the JSON files by specifying the new values using environment variables or CLI parameters, eg :
dotnet run /ConnectionStrings:blahblah="......."
Without a generic host
You can create just the Configuration object by using a ConfigurationBuilder:
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
var connectionString=config.GetConnectionString("blahblah");
Related
Using the AWS .NET Core 3.1 Mock Lambda Test Tool, I cannot get the lambda function to read from an appsettings.json or even an app.config file.
That is two sperate methods that when I try to get a return value, each method returns null.
In a separate .NET Core 3.1 console app, these same methods work perfectly fine.
So, is there some reason why the 'Mock Lambda Test Tool' at runtime will not allow my code to read from a JSON or App.config file set to copy-always? And does this mean this will not run on AWS when packaged and uploaded to the AWS Lambda console?
My situation does not allow me to use Lambda Environment Variables for my local DB connection string. And I cannot store the connection string inside the code, as it has to come from a .json or .config file.
Any ideas or wisdom on this?
THE CODE:
METHOD 1
// requires: System.Configuration.ConfigurationManager
var connString = System.Configuration.ConfigurationManager.AppSettings["connectionString"];
/*
Reads App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="connectionString" value="Server=127.0.0.1;Port=0000;Database=some-db;User Id=some-user;Password=some-password;" />
</appSettings>
</configuration>
*/
METHOD 2
// requires: Microsoft.Extensions.Configuration; Microsoft.Extensions.Configuration.Json;
public class DbConfig
{
public string ConnectionString { get; set; }
}
var config = new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json").Build();
var section = config.GetSection(nameof(DbConfig));
var dbClientConfig = section.Get<DbConfig>();
var connString = dbClientConfig.ConnectionString;
/*
Reads appsettings.json:
{
"DbConfig": {
"connectionString": "Server=127.0.0.1;Port=0000;Database=some-db;User Id=some-user;Password=some-password;"
}
}
*/
I also used a simpler bare-bones method, that also works in console app but not in the Lambda.
METHOD 3:
// requires: Microsoft.Extensions.Configuration;
IConfiguration _config = new ConfigurationBuilder().AddJsonFile("appconfig.json", true, true).Build();
var _connString = _config["connectionString"];
/*
Reads appconfig.json:
{
"connectionString": "Server=127.0.0.1;Port=0000;Database=some-db;User Id=some-user;Password=some-password;"
}
*/
Again, thanks.
From this blog post
The test tool is an ASP.NET Core application that loads and executes the Lambda code.
Which means that this web app has its own config file that is different from your application's one. And if you put a breakpoint in startup class, you will see that configuration has different fields kept in rather that those in your appsettings.json or whatever file.
solution #1
Register current directory as a folder where to search config files
new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true)
I've got a method that reads settings from my config file like this:
var value = ConfigurationManager.AppSettings[key];
It compiles fine when targeting .NET Standard 2.0 only.
Now I need multiple targets, so I updated my project file with:
<TargetFrameworks>netcoreapp2.0;net461;netstandard2.0</TargetFrameworks>
But now, the compilation fails for netcoreapp2.0 with the following error message:
Error CS0103 The name 'ConfigurationManager' does not exist in the current context (netcoreapp2.0)
Separately, I created a new .NET Core 2.0 console application (only targeting .NET Core 2.0 this time), but likewise there seems to be no ConfigurationManager under the namespace System.Configuration.
I'm quite confused because it's available under .NET Standard 2.0, so I would expect it to be available in .NET Core 2.0, as .NET Core 2.0 is .NET Standard 2.0 compliant.
What am I missing?
Yes, ConfigurationManager.AppSettings is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager.
Credits goes to #JeroenMostert for giving me the solution.
I installed System.Configuration.ConfigurationManager from Nuget into my .net core 2.2 application.
I then reference using System.Configuration;
Next, I changed
WebConfigurationManager.AppSettings
to ..
ConfigurationManager.AppSettings
So far I believe this is correct. 4.5.0 is typical with .net core 2.2
I have not had any issues with this.
Once you have the packages setup, you'll need to create either an app.config or web.config and add something like the following:
<configuration>
<appSettings>
<add key="key" value="value"/>
</appSettings>
</configuration>
The latest set of guidance is as follows: (from https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)
Use:
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
From the docs:
public static class EnvironmentVariablesExample
{
[FunctionName("GetEnvironmentVariables")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
}
public static string GetEnvironmentVariable(string name)
{
return name + ": " +
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
}
App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("<app setting name>") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.
The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.
I used below code example. Also this is so convenient way.
using Microsoft.Extensions.Configuration;
using System.IO;
namespace DemoWeppApp
{
public static class StaticConfigurationManager
{
public static IConfiguration AppSetting { get; }
static StaticConfigurationManager()
{
AppSetting = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
}
}
}
And then I can use easly in any static class like this
StaticConfigurationManager.AppSetting["conf_name"];
You can use Configuration to resolve this.
Ex (Startup.cs):
You can pass by DI to the controllers after this implementation.
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var microserviceName = Configuration["microserviceName"];
services.AddSingleton(Configuration);
...
}
I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app.
in API constructor add the following:
public class TargetClassController : ControllerBase
{
private readonly IConfiguration _config;
public TargetClassController(IConfiguration config)
{
_config = config;
}
[HttpGet("{id:int}")]
public async Task<ActionResult<DTOResponse>> Get(int id)
{
var config = _config["YourKeySection:key"];
}
}
I am attempting to use entity framework against a database in Azure. I have a connection string stored in the local.settings.json, but all of my attempts to reference it from a Startup.cs have failed.
I am able to access my connection string using an IConfiguration DI into a function class and I can successfully access the database with SQL Command using the configuration like:
string connectionString = _configuration.GetConnectionString("cpni");
So I know that the connection string is working and that I can access it.
If I try to use DI with IConfiguration on the Startup class, the compiler does not give me any errors, but once it's running in debug I begin getting the following error:
System.Private.CoreLib: No parameterless constructor defined for type 'CPNI_Functions.Startup'.
Here is what I'm currently successfully using with a hardcoded connectionString (since using DI with IConfiguration isn't working):
builder.Services.AddDbContext<CpniContext>(
options => options.UseSqlServer(connectionString));
And that allows me to work with the database through EF. What I would like to use is some combination of that and something like this:
builder.Services.AddDbContext<CpniContext>(/*options need to go here?*/)
.Configure<IConfiguration>((configuration) =>
{
//Or are options supposed to go here somewhere, or be bound here with some sort of .Bind()?
configuration.GetConnectionString("cpni");
});
If that doesn't make sense or won't work, then please let me know what the recommended way of setting this DI up is. If possible, I want to avoid using configuration lookup through ConfigurationManager.
For reference, here is the full Startup.cs and this works:
using CPNI_Functions.Data;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(CPNI_Functions.Startup))]
namespace CPNI_Functions
{
class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
string connectionString = "myconnectionstringhere";
builder.Services.AddDbContext<CpniContext>(
options => options.UseSqlServer(connectionString));
}
/*
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CpniContext>(configuration.GetConnectionString("cpni"));
}*/
}
}
I'm new to core and I'm new to Azure Functions, so please forgive my ignorance on this. Thank you in advance for your help.
For an Azure function app you could try adding NuGet package:
System.Configuration.ConfigurationManager
local.settings.json:
{
"ConnectionStrings": {
"cpni": "[ConnectionStringDetails]"
}
}
Then hopefully you should be able to access using ConfigurationManager.
services.AddDbContext<CpniContext>(
options => options.UseSqlServer(ConfigurationManager.ConnectionStrings["cpni"].ConnectionString));
I've got a method that reads settings from my config file like this:
var value = ConfigurationManager.AppSettings[key];
It compiles fine when targeting .NET Standard 2.0 only.
Now I need multiple targets, so I updated my project file with:
<TargetFrameworks>netcoreapp2.0;net461;netstandard2.0</TargetFrameworks>
But now, the compilation fails for netcoreapp2.0 with the following error message:
Error CS0103 The name 'ConfigurationManager' does not exist in the current context (netcoreapp2.0)
Separately, I created a new .NET Core 2.0 console application (only targeting .NET Core 2.0 this time), but likewise there seems to be no ConfigurationManager under the namespace System.Configuration.
I'm quite confused because it's available under .NET Standard 2.0, so I would expect it to be available in .NET Core 2.0, as .NET Core 2.0 is .NET Standard 2.0 compliant.
What am I missing?
Yes, ConfigurationManager.AppSettings is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager.
Credits goes to #JeroenMostert for giving me the solution.
I installed System.Configuration.ConfigurationManager from Nuget into my .net core 2.2 application.
I then reference using System.Configuration;
Next, I changed
WebConfigurationManager.AppSettings
to ..
ConfigurationManager.AppSettings
So far I believe this is correct. 4.5.0 is typical with .net core 2.2
I have not had any issues with this.
Once you have the packages setup, you'll need to create either an app.config or web.config and add something like the following:
<configuration>
<appSettings>
<add key="key" value="value"/>
</appSettings>
</configuration>
The latest set of guidance is as follows: (from https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)
Use:
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
From the docs:
public static class EnvironmentVariablesExample
{
[FunctionName("GetEnvironmentVariables")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
}
public static string GetEnvironmentVariable(string name)
{
return name + ": " +
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
}
App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("<app setting name>") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.
The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.
I used below code example. Also this is so convenient way.
using Microsoft.Extensions.Configuration;
using System.IO;
namespace DemoWeppApp
{
public static class StaticConfigurationManager
{
public static IConfiguration AppSetting { get; }
static StaticConfigurationManager()
{
AppSetting = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
}
}
}
And then I can use easly in any static class like this
StaticConfigurationManager.AppSetting["conf_name"];
You can use Configuration to resolve this.
Ex (Startup.cs):
You can pass by DI to the controllers after this implementation.
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var microserviceName = Configuration["microserviceName"];
services.AddSingleton(Configuration);
...
}
I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app.
in API constructor add the following:
public class TargetClassController : ControllerBase
{
private readonly IConfiguration _config;
public TargetClassController(IConfiguration config)
{
_config = config;
}
[HttpGet("{id:int}")]
public async Task<ActionResult<DTOResponse>> Get(int id)
{
var config = _config["YourKeySection:key"];
}
}
I have a Visual Studio 2015 solution made up of projects targeting DNX framework. I have been working locally but I plan to deploy to Azure environments (dev/test/prod). Naturally, the solution uses different database connection strings and other variables dependent on the environment. In the past I made use of cloud configuration files to set these variables, reading them with the CloudConfigurationManager.
I am given to understand that I need to use a config.json file. I have the following code in my Startup.cs file:
public Startup(IHostingEnvironment env, IApplicationEnvironment app)
{
Configuration = new ConfigurationBuilder(app.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
Configuration.Set("ASPNET_ENV", "Development");
}
My config.json file is currently an empty object { }. How do I add variables to this file (syntax?), and how do I access them from code?
Note this line in your startup code:
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
This adds an additional JSON config file which is named depending on your environment name. So add a new file to your project called:
config.<environment-name>.json
And set up the details in there, such as:
{
"AppSettings": {
"SomeVariable": "Blah"
},
"Data": {
"YourConnectionString": {
"ConnectionString": "<connection string here>"
}
}
}
For reading the configuration, there's a good answer here: Using IConfiguration globally in mvc6
You can use plain old JSON for that. For example, here's how to define a connection string:
{
"Foo": "Bar"
}
To access the configuration value, you do:
config.Get("username")
or:
config["username"];
You can find more information here: http://docs.asp.net/en/latest/fundamentals/configuration.html