How to read AppSettings values from .json file in ASP.NET Core
I have setup my AppSettings data in appsettings/Config .json like this:
{
"AppSettings": {
"token": "1234"
}
}
I have searched online on how to read AppSettings values from .json file, but I could not get anything useful.
I tried:
var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null
I know with ASP.NET 4.0 you can do this:
System.Configuration.ConfigurationManager.AppSettings["token"];
But how do I do this in ASP.NET Core?
c# asp.net asp.net-core config.json
add a comment |
I have setup my AppSettings data in appsettings/Config .json like this:
{
"AppSettings": {
"token": "1234"
}
}
I have searched online on how to read AppSettings values from .json file, but I could not get anything useful.
I tried:
var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null
I know with ASP.NET 4.0 you can do this:
System.Configuration.ConfigurationManager.AppSettings["token"];
But how do I do this in ASP.NET Core?
c# asp.net asp.net-core config.json
possible duplicate of ASP.NET 5 (vNext) - Getting a Configuration Setting
– mason
Jul 16 '15 at 13:20
A reference MSDN that provides additional insight.
– MDMoore313
Nov 18 '17 at 22:06
this can be even simplified just by using dependency injection of IConfiguration (in .net core 2.0). Which is explained here coding-issues.com/2018/10/…
– Ranadheer Reddy
Oct 9 '18 at 14:27
add a comment |
I have setup my AppSettings data in appsettings/Config .json like this:
{
"AppSettings": {
"token": "1234"
}
}
I have searched online on how to read AppSettings values from .json file, but I could not get anything useful.
I tried:
var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null
I know with ASP.NET 4.0 you can do this:
System.Configuration.ConfigurationManager.AppSettings["token"];
But how do I do this in ASP.NET Core?
c# asp.net asp.net-core config.json
I have setup my AppSettings data in appsettings/Config .json like this:
{
"AppSettings": {
"token": "1234"
}
}
I have searched online on how to read AppSettings values from .json file, but I could not get anything useful.
I tried:
var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null
I know with ASP.NET 4.0 you can do this:
System.Configuration.ConfigurationManager.AppSettings["token"];
But how do I do this in ASP.NET Core?
c# asp.net asp.net-core config.json
c# asp.net asp.net-core config.json
edited Dec 1 '18 at 9:22
S.Serpooshan
4,12821637
4,12821637
asked Jul 16 '15 at 11:57
OluwafemiOluwafemi
5,77693355
5,77693355
possible duplicate of ASP.NET 5 (vNext) - Getting a Configuration Setting
– mason
Jul 16 '15 at 13:20
A reference MSDN that provides additional insight.
– MDMoore313
Nov 18 '17 at 22:06
this can be even simplified just by using dependency injection of IConfiguration (in .net core 2.0). Which is explained here coding-issues.com/2018/10/…
– Ranadheer Reddy
Oct 9 '18 at 14:27
add a comment |
possible duplicate of ASP.NET 5 (vNext) - Getting a Configuration Setting
– mason
Jul 16 '15 at 13:20
A reference MSDN that provides additional insight.
– MDMoore313
Nov 18 '17 at 22:06
this can be even simplified just by using dependency injection of IConfiguration (in .net core 2.0). Which is explained here coding-issues.com/2018/10/…
– Ranadheer Reddy
Oct 9 '18 at 14:27
possible duplicate of ASP.NET 5 (vNext) - Getting a Configuration Setting
– mason
Jul 16 '15 at 13:20
possible duplicate of ASP.NET 5 (vNext) - Getting a Configuration Setting
– mason
Jul 16 '15 at 13:20
A reference MSDN that provides additional insight.
– MDMoore313
Nov 18 '17 at 22:06
A reference MSDN that provides additional insight.
– MDMoore313
Nov 18 '17 at 22:06
this can be even simplified just by using dependency injection of IConfiguration (in .net core 2.0). Which is explained here coding-issues.com/2018/10/…
– Ranadheer Reddy
Oct 9 '18 at 14:27
this can be even simplified just by using dependency injection of IConfiguration (in .net core 2.0). Which is explained here coding-issues.com/2018/10/…
– Ranadheer Reddy
Oct 9 '18 at 14:27
add a comment |
11 Answers
11
active
oldest
votes
This has had a few twists and turns. I've modified this answer to be up to date with ASP.NET Core 2.0 (as of 26/02/2018).
This is mostly taken from the official documentation:
To work with settings in your ASP.NET application, it is recommended that you only instantiate a Configuration
in your application’s Startup
class. Then, use the Options pattern to access individual settings. Let's say we have an appsettings.json
file that looks like this:
{
"MyConfig": {
"ApplicationName": "MyApp",
"Version": "1.0.0"
}
}
And we have a POCO object representing the configuration:
public class MyConfig
{
public string ApplicationName { get; set; }
public int Version { get; set; }
}
Now we build the configuration in Startup.cs
:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
}
Note that appsettings.json
will be registered by default in .NET Core 2.0. We can also register an appsettings.{Environment}.json
config file per environment if needed.
If we want to inject our configuration to our controllers, we'll need to register it with the runtime. We do so via Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
And we inject it like this:
public class HomeController : Controller
{
private readonly IOptions<MyConfig> config;
public HomeController(IOptions<MyConfig> config)
{
this.config = config;
}
// GET: /<controller>/
public IActionResult Index() => View(config.Value);
}
The full Startup
class:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
}
3
version"1.0.0-beta4"
works on mine not"1.0.0-alpha4"
. Thanks a lot!
– Oluwafemi
Jul 16 '15 at 12:20
1
I need to pass a setting to another layer from a utility class so I need something like this public static string GetConnectionString() { if (string.IsNullOrEmpty(connectionString)) { var builder = new ConfigurationBuilder() .AddJsonFile("config.json"); Configuration = builder.Build(); connectionString = Configuration.Get("Data:DefaultConnection:ConnectionString"); } } return connectionString; }
– dnxit
Aug 18 '15 at 20:52
2
I getArgument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<....Settings>'
– Peter
Apr 20 '18 at 20:23
1
@YuvalItzchakov on the following line.Configure<Settings>(Configuration.GetSection("Settings"))
– Peter
Apr 20 '18 at 20:55
2
After adding the nugetMicrosoft.Extensions.Options.ConfigurationExtensions
it worked as expected.
– Peter
Apr 20 '18 at 22:19
|
show 14 more comments
First off:
The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use:
e.g.
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
as a dependency in project.json
. Use beta5 or 6 if you don't have 7 installed.
Then you can do something like this in Startup.cs
.
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
}
If you then want to retrieve a variable from the config.json you can get it right away using:
public void Configure(IApplicationBuilder app)
{
// Add .Value to get the token string
var token = Configuration.GetSection("AppSettings:token");
app.Run(async (context) =>
{
await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
});
}
or you can create a class called AppSettings like this:
public class AppSettings
{
public string token { get; set; }
}
and configure the services like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
//mvc options
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
and then access it through e.g. a controller like this:
public class HomeController : Controller
{
private string _token;
public HomeController(IOptions<AppSettings> settings)
{
_token = settings.Options.token;
}
}
can you please share configuration json for "AppSettings" for reference
– Ankit
May 2 '18 at 13:18
I need entire appSettings.json configs in class, for this, I have designed class as per JSON and useConfiguration.Get<AppSettings>()
to deserialize entire file instead of a specific section.
– Nilay
Jul 31 '18 at 1:06
add a comment |
For .NET Core 2.0, things have changed a little bit. The startup constructor takes a Configuration object as a parameter, So using the ConfigurationBuilder
is not required. Here is mine:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig"));
}
My POCO is the StorageOptions
object mentioned at the top:
namespace Brazzers.Models
{
public class StorageOptions
{
public String StorageConnectionString { get; set; }
public String AccountName { get; set; }
public String AccountKey { get; set; }
public String DefaultEndpointsProtocol { get; set; }
public String EndpointSuffix { get; set; }
public StorageOptions() { }
}
}
And the configuration is actually a subsection of my appsettings.json
file, named AzureStorageConfig
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AzureStorageConfig": {
"AccountName": "brazzerswebapp",
"AccountKey": "Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==",
"DefaultEndpointsProtocol": "https",
"EndpointSuffix": "core.windows.net",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
}
}
The only thing I'll add is that, since the constructor has changed, I haven't tested whether something extra needs to be done for it to load appsettings.<environmentname>.json
as opposed to appsettings.json
.
39
Soo cool you work for brazzers!!
– Ivan Juarez
Dec 16 '17 at 19:10
Just a note that you still need to toss .AddJsonFile("yourfile.json") to ConfigConfiguration. IE, you need to tell it where the file is. Didn't see that in the answer.
– Eric
Mar 12 '18 at 17:06
Eric I will retest that, I don't remember adding that line; Could it be necessary only if the name of the json file isn't the default name?
– MDMoore313
Mar 12 '18 at 17:31
Per MSDN, it is not required for ASPNETCORE 2.0, although it doesnt appear to work for me either. docs.microsoft.com/en-us/dotnet/api/…
– Sat Thiru
Mar 26 '18 at 4:47
1
Can you give an example how you inject StorageOptions into your controllers? If I use hug's approach of using dependency injection withpublic HomeController(IOptions<StorageOptions> settings)
, I get this error message: Model bound complex types must not be abstract or value types and must have a parameterless constructor.
– Jpsy
May 3 '18 at 9:21
|
show 2 more comments
If you just want to get the value of the token then use
Configuration["AppSettings:token"]
add a comment |
For .NET Core 2.0, you can simply:
Declare your key/value pairs in appsettings.json:
{
"MyKey": "MyValue
}
Inject the configuration service in startup.cs, and get the value using the service
using Microsoft.Extensions.Configuration;
public class Startup
{
public void Configure(IConfiguration configuration,
... other injected services
)
{
app.Run(async (context) =>
{
string myValue = configuration["MyKey"];
await context.Response.WriteAsync(myValue);
});
add a comment |
Following works for Console Apps;
1- install following nuget
packages (.csproj
);
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
</ItemGroup>
2- Create appsettings.json
at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".
3- Sample config file:
{
"AppConfig": {
"FilePath": "C:\temp\logs\output.txt"
}
}
4- Program.cs
configurationSection.Key
and configurationSection.Value
will have config properties.
static void Main(string args)
{
try
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
// configurationSection.Key => FilePath
// configurationSection.Value => C:\temp\logs\output.txt
IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
add a comment |
Just to complement the Yuval Itzchakov answer.
You can load configuration without builder function, you can just inject it.
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
add a comment |
They just keep changing things – having just updated VS and had the whole project bomb, on the road to recovery and the new way looks like this:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
I kept missing this line!
.SetBasePath(env.ContentRootPath)
1
How can we get the AppSettings values in Test Projects using the same approach?
– S.Siva
Sep 30 '16 at 10:40
add a comment |
So I doubt this is good practice but it's working locally, I'll update this if it fails when I publish/deploy (to an IIS web service).
Step 1.) Add this assembly to the top of your class (in my case, controller class):
using Microsoft.Extensions.Configuration;
Step 2.) Add this or something like it:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
Step 3.) Call your key's value by doing this (returns string):
config["NameOfYourKey"]
add a comment |
In addition to existing answers I'd like to mention that sometimes it might be useful to have extension methods for IConfiguration
for simplicity's sake.
I keep JWT config in appsettings.json so my extension methods class looks as follows:
public static class ConfigurationExtensions
{
public static string GetIssuerSigningKey(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
return result;
}
public static string GetValidIssuer(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
return result;
}
public static string GetValidAudience(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
return result;
}
public static string GetDefaultPolicy(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Policies:Default");
return result;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
{
var issuerSigningKey = configuration.GetIssuerSigningKey();
var data = Encoding.UTF8.GetBytes(issuerSigningKey);
var result = new SymmetricSecurityKey(data);
return result;
}
public static string GetCorsOrigins(this IConfiguration configuration)
{
string result =
configuration.GetValue<string>("App:CorsOrigins")
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.ToArray();
return result;
}
}
It saves you a lot of lines and you just write clean and minimal code:
...
x.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
ValidAudience = _configuration.GetValidAudience(),
ValidIssuer = _configuration.GetValidIssuer()
};
It's also possible to register IConfiguration
instance as singleton and inject it wherever you need - I use Autofac container here's how you do it:
var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();
You can do the same with MS Dependency Injection:
services.AddSingleton<IConfigurationRoot>(appConfiguration);
add a comment |
Was this "cheating"? I just made my Configuration in the Startup class static, and then I can access it from anywhere else:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public static IConfiguration Configuration { get; set; }
add a comment |
protected by Yuval Itzchakov Feb 3 at 5:27
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
This has had a few twists and turns. I've modified this answer to be up to date with ASP.NET Core 2.0 (as of 26/02/2018).
This is mostly taken from the official documentation:
To work with settings in your ASP.NET application, it is recommended that you only instantiate a Configuration
in your application’s Startup
class. Then, use the Options pattern to access individual settings. Let's say we have an appsettings.json
file that looks like this:
{
"MyConfig": {
"ApplicationName": "MyApp",
"Version": "1.0.0"
}
}
And we have a POCO object representing the configuration:
public class MyConfig
{
public string ApplicationName { get; set; }
public int Version { get; set; }
}
Now we build the configuration in Startup.cs
:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
}
Note that appsettings.json
will be registered by default in .NET Core 2.0. We can also register an appsettings.{Environment}.json
config file per environment if needed.
If we want to inject our configuration to our controllers, we'll need to register it with the runtime. We do so via Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
And we inject it like this:
public class HomeController : Controller
{
private readonly IOptions<MyConfig> config;
public HomeController(IOptions<MyConfig> config)
{
this.config = config;
}
// GET: /<controller>/
public IActionResult Index() => View(config.Value);
}
The full Startup
class:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
}
3
version"1.0.0-beta4"
works on mine not"1.0.0-alpha4"
. Thanks a lot!
– Oluwafemi
Jul 16 '15 at 12:20
1
I need to pass a setting to another layer from a utility class so I need something like this public static string GetConnectionString() { if (string.IsNullOrEmpty(connectionString)) { var builder = new ConfigurationBuilder() .AddJsonFile("config.json"); Configuration = builder.Build(); connectionString = Configuration.Get("Data:DefaultConnection:ConnectionString"); } } return connectionString; }
– dnxit
Aug 18 '15 at 20:52
2
I getArgument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<....Settings>'
– Peter
Apr 20 '18 at 20:23
1
@YuvalItzchakov on the following line.Configure<Settings>(Configuration.GetSection("Settings"))
– Peter
Apr 20 '18 at 20:55
2
After adding the nugetMicrosoft.Extensions.Options.ConfigurationExtensions
it worked as expected.
– Peter
Apr 20 '18 at 22:19
|
show 14 more comments
This has had a few twists and turns. I've modified this answer to be up to date with ASP.NET Core 2.0 (as of 26/02/2018).
This is mostly taken from the official documentation:
To work with settings in your ASP.NET application, it is recommended that you only instantiate a Configuration
in your application’s Startup
class. Then, use the Options pattern to access individual settings. Let's say we have an appsettings.json
file that looks like this:
{
"MyConfig": {
"ApplicationName": "MyApp",
"Version": "1.0.0"
}
}
And we have a POCO object representing the configuration:
public class MyConfig
{
public string ApplicationName { get; set; }
public int Version { get; set; }
}
Now we build the configuration in Startup.cs
:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
}
Note that appsettings.json
will be registered by default in .NET Core 2.0. We can also register an appsettings.{Environment}.json
config file per environment if needed.
If we want to inject our configuration to our controllers, we'll need to register it with the runtime. We do so via Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
And we inject it like this:
public class HomeController : Controller
{
private readonly IOptions<MyConfig> config;
public HomeController(IOptions<MyConfig> config)
{
this.config = config;
}
// GET: /<controller>/
public IActionResult Index() => View(config.Value);
}
The full Startup
class:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
}
3
version"1.0.0-beta4"
works on mine not"1.0.0-alpha4"
. Thanks a lot!
– Oluwafemi
Jul 16 '15 at 12:20
1
I need to pass a setting to another layer from a utility class so I need something like this public static string GetConnectionString() { if (string.IsNullOrEmpty(connectionString)) { var builder = new ConfigurationBuilder() .AddJsonFile("config.json"); Configuration = builder.Build(); connectionString = Configuration.Get("Data:DefaultConnection:ConnectionString"); } } return connectionString; }
– dnxit
Aug 18 '15 at 20:52
2
I getArgument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<....Settings>'
– Peter
Apr 20 '18 at 20:23
1
@YuvalItzchakov on the following line.Configure<Settings>(Configuration.GetSection("Settings"))
– Peter
Apr 20 '18 at 20:55
2
After adding the nugetMicrosoft.Extensions.Options.ConfigurationExtensions
it worked as expected.
– Peter
Apr 20 '18 at 22:19
|
show 14 more comments
This has had a few twists and turns. I've modified this answer to be up to date with ASP.NET Core 2.0 (as of 26/02/2018).
This is mostly taken from the official documentation:
To work with settings in your ASP.NET application, it is recommended that you only instantiate a Configuration
in your application’s Startup
class. Then, use the Options pattern to access individual settings. Let's say we have an appsettings.json
file that looks like this:
{
"MyConfig": {
"ApplicationName": "MyApp",
"Version": "1.0.0"
}
}
And we have a POCO object representing the configuration:
public class MyConfig
{
public string ApplicationName { get; set; }
public int Version { get; set; }
}
Now we build the configuration in Startup.cs
:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
}
Note that appsettings.json
will be registered by default in .NET Core 2.0. We can also register an appsettings.{Environment}.json
config file per environment if needed.
If we want to inject our configuration to our controllers, we'll need to register it with the runtime. We do so via Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
And we inject it like this:
public class HomeController : Controller
{
private readonly IOptions<MyConfig> config;
public HomeController(IOptions<MyConfig> config)
{
this.config = config;
}
// GET: /<controller>/
public IActionResult Index() => View(config.Value);
}
The full Startup
class:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
}
This has had a few twists and turns. I've modified this answer to be up to date with ASP.NET Core 2.0 (as of 26/02/2018).
This is mostly taken from the official documentation:
To work with settings in your ASP.NET application, it is recommended that you only instantiate a Configuration
in your application’s Startup
class. Then, use the Options pattern to access individual settings. Let's say we have an appsettings.json
file that looks like this:
{
"MyConfig": {
"ApplicationName": "MyApp",
"Version": "1.0.0"
}
}
And we have a POCO object representing the configuration:
public class MyConfig
{
public string ApplicationName { get; set; }
public int Version { get; set; }
}
Now we build the configuration in Startup.cs
:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
}
Note that appsettings.json
will be registered by default in .NET Core 2.0. We can also register an appsettings.{Environment}.json
config file per environment if needed.
If we want to inject our configuration to our controllers, we'll need to register it with the runtime. We do so via Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
And we inject it like this:
public class HomeController : Controller
{
private readonly IOptions<MyConfig> config;
public HomeController(IOptions<MyConfig> config)
{
this.config = config;
}
// GET: /<controller>/
public IActionResult Index() => View(config.Value);
}
The full Startup
class:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
}
edited Oct 11 '18 at 17:43
Pranay Aryal
2,54421627
2,54421627
answered Jul 16 '15 at 12:05
Yuval ItzchakovYuval Itzchakov
115k26172240
115k26172240
3
version"1.0.0-beta4"
works on mine not"1.0.0-alpha4"
. Thanks a lot!
– Oluwafemi
Jul 16 '15 at 12:20
1
I need to pass a setting to another layer from a utility class so I need something like this public static string GetConnectionString() { if (string.IsNullOrEmpty(connectionString)) { var builder = new ConfigurationBuilder() .AddJsonFile("config.json"); Configuration = builder.Build(); connectionString = Configuration.Get("Data:DefaultConnection:ConnectionString"); } } return connectionString; }
– dnxit
Aug 18 '15 at 20:52
2
I getArgument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<....Settings>'
– Peter
Apr 20 '18 at 20:23
1
@YuvalItzchakov on the following line.Configure<Settings>(Configuration.GetSection("Settings"))
– Peter
Apr 20 '18 at 20:55
2
After adding the nugetMicrosoft.Extensions.Options.ConfigurationExtensions
it worked as expected.
– Peter
Apr 20 '18 at 22:19
|
show 14 more comments
3
version"1.0.0-beta4"
works on mine not"1.0.0-alpha4"
. Thanks a lot!
– Oluwafemi
Jul 16 '15 at 12:20
1
I need to pass a setting to another layer from a utility class so I need something like this public static string GetConnectionString() { if (string.IsNullOrEmpty(connectionString)) { var builder = new ConfigurationBuilder() .AddJsonFile("config.json"); Configuration = builder.Build(); connectionString = Configuration.Get("Data:DefaultConnection:ConnectionString"); } } return connectionString; }
– dnxit
Aug 18 '15 at 20:52
2
I getArgument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<....Settings>'
– Peter
Apr 20 '18 at 20:23
1
@YuvalItzchakov on the following line.Configure<Settings>(Configuration.GetSection("Settings"))
– Peter
Apr 20 '18 at 20:55
2
After adding the nugetMicrosoft.Extensions.Options.ConfigurationExtensions
it worked as expected.
– Peter
Apr 20 '18 at 22:19
3
3
version
"1.0.0-beta4"
works on mine not "1.0.0-alpha4"
. Thanks a lot!– Oluwafemi
Jul 16 '15 at 12:20
version
"1.0.0-beta4"
works on mine not "1.0.0-alpha4"
. Thanks a lot!– Oluwafemi
Jul 16 '15 at 12:20
1
1
I need to pass a setting to another layer from a utility class so I need something like this public static string GetConnectionString() { if (string.IsNullOrEmpty(connectionString)) { var builder = new ConfigurationBuilder() .AddJsonFile("config.json"); Configuration = builder.Build(); connectionString = Configuration.Get("Data:DefaultConnection:ConnectionString"); } } return connectionString; }
– dnxit
Aug 18 '15 at 20:52
I need to pass a setting to another layer from a utility class so I need something like this public static string GetConnectionString() { if (string.IsNullOrEmpty(connectionString)) { var builder = new ConfigurationBuilder() .AddJsonFile("config.json"); Configuration = builder.Build(); connectionString = Configuration.Get("Data:DefaultConnection:ConnectionString"); } } return connectionString; }
– dnxit
Aug 18 '15 at 20:52
2
2
I get
Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<....Settings>'
– Peter
Apr 20 '18 at 20:23
I get
Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action<....Settings>'
– Peter
Apr 20 '18 at 20:23
1
1
@YuvalItzchakov on the following line
.Configure<Settings>(Configuration.GetSection("Settings"))
– Peter
Apr 20 '18 at 20:55
@YuvalItzchakov on the following line
.Configure<Settings>(Configuration.GetSection("Settings"))
– Peter
Apr 20 '18 at 20:55
2
2
After adding the nuget
Microsoft.Extensions.Options.ConfigurationExtensions
it worked as expected.– Peter
Apr 20 '18 at 22:19
After adding the nuget
Microsoft.Extensions.Options.ConfigurationExtensions
it worked as expected.– Peter
Apr 20 '18 at 22:19
|
show 14 more comments
First off:
The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use:
e.g.
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
as a dependency in project.json
. Use beta5 or 6 if you don't have 7 installed.
Then you can do something like this in Startup.cs
.
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
}
If you then want to retrieve a variable from the config.json you can get it right away using:
public void Configure(IApplicationBuilder app)
{
// Add .Value to get the token string
var token = Configuration.GetSection("AppSettings:token");
app.Run(async (context) =>
{
await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
});
}
or you can create a class called AppSettings like this:
public class AppSettings
{
public string token { get; set; }
}
and configure the services like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
//mvc options
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
and then access it through e.g. a controller like this:
public class HomeController : Controller
{
private string _token;
public HomeController(IOptions<AppSettings> settings)
{
_token = settings.Options.token;
}
}
can you please share configuration json for "AppSettings" for reference
– Ankit
May 2 '18 at 13:18
I need entire appSettings.json configs in class, for this, I have designed class as per JSON and useConfiguration.Get<AppSettings>()
to deserialize entire file instead of a specific section.
– Nilay
Jul 31 '18 at 1:06
add a comment |
First off:
The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use:
e.g.
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
as a dependency in project.json
. Use beta5 or 6 if you don't have 7 installed.
Then you can do something like this in Startup.cs
.
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
}
If you then want to retrieve a variable from the config.json you can get it right away using:
public void Configure(IApplicationBuilder app)
{
// Add .Value to get the token string
var token = Configuration.GetSection("AppSettings:token");
app.Run(async (context) =>
{
await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
});
}
or you can create a class called AppSettings like this:
public class AppSettings
{
public string token { get; set; }
}
and configure the services like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
//mvc options
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
and then access it through e.g. a controller like this:
public class HomeController : Controller
{
private string _token;
public HomeController(IOptions<AppSettings> settings)
{
_token = settings.Options.token;
}
}
can you please share configuration json for "AppSettings" for reference
– Ankit
May 2 '18 at 13:18
I need entire appSettings.json configs in class, for this, I have designed class as per JSON and useConfiguration.Get<AppSettings>()
to deserialize entire file instead of a specific section.
– Nilay
Jul 31 '18 at 1:06
add a comment |
First off:
The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use:
e.g.
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
as a dependency in project.json
. Use beta5 or 6 if you don't have 7 installed.
Then you can do something like this in Startup.cs
.
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
}
If you then want to retrieve a variable from the config.json you can get it right away using:
public void Configure(IApplicationBuilder app)
{
// Add .Value to get the token string
var token = Configuration.GetSection("AppSettings:token");
app.Run(async (context) =>
{
await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
});
}
or you can create a class called AppSettings like this:
public class AppSettings
{
public string token { get; set; }
}
and configure the services like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
//mvc options
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
and then access it through e.g. a controller like this:
public class HomeController : Controller
{
private string _token;
public HomeController(IOptions<AppSettings> settings)
{
_token = settings.Options.token;
}
}
First off:
The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use:
e.g.
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"
as a dependency in project.json
. Use beta5 or 6 if you don't have 7 installed.
Then you can do something like this in Startup.cs
.
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = configurationBuilder.Build();
}
If you then want to retrieve a variable from the config.json you can get it right away using:
public void Configure(IApplicationBuilder app)
{
// Add .Value to get the token string
var token = Configuration.GetSection("AppSettings:token");
app.Run(async (context) =>
{
await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
});
}
or you can create a class called AppSettings like this:
public class AppSettings
{
public string token { get; set; }
}
and configure the services like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
//mvc options
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
and then access it through e.g. a controller like this:
public class HomeController : Controller
{
private string _token;
public HomeController(IOptions<AppSettings> settings)
{
_token = settings.Options.token;
}
}
edited Mar 26 '18 at 9:28
Massimiliano Kraus
2,36941632
2,36941632
answered Sep 23 '15 at 15:27
hughug
72067
72067
can you please share configuration json for "AppSettings" for reference
– Ankit
May 2 '18 at 13:18
I need entire appSettings.json configs in class, for this, I have designed class as per JSON and useConfiguration.Get<AppSettings>()
to deserialize entire file instead of a specific section.
– Nilay
Jul 31 '18 at 1:06
add a comment |
can you please share configuration json for "AppSettings" for reference
– Ankit
May 2 '18 at 13:18
I need entire appSettings.json configs in class, for this, I have designed class as per JSON and useConfiguration.Get<AppSettings>()
to deserialize entire file instead of a specific section.
– Nilay
Jul 31 '18 at 1:06
can you please share configuration json for "AppSettings" for reference
– Ankit
May 2 '18 at 13:18
can you please share configuration json for "AppSettings" for reference
– Ankit
May 2 '18 at 13:18
I need entire appSettings.json configs in class, for this, I have designed class as per JSON and use
Configuration.Get<AppSettings>()
to deserialize entire file instead of a specific section.– Nilay
Jul 31 '18 at 1:06
I need entire appSettings.json configs in class, for this, I have designed class as per JSON and use
Configuration.Get<AppSettings>()
to deserialize entire file instead of a specific section.– Nilay
Jul 31 '18 at 1:06
add a comment |
For .NET Core 2.0, things have changed a little bit. The startup constructor takes a Configuration object as a parameter, So using the ConfigurationBuilder
is not required. Here is mine:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig"));
}
My POCO is the StorageOptions
object mentioned at the top:
namespace Brazzers.Models
{
public class StorageOptions
{
public String StorageConnectionString { get; set; }
public String AccountName { get; set; }
public String AccountKey { get; set; }
public String DefaultEndpointsProtocol { get; set; }
public String EndpointSuffix { get; set; }
public StorageOptions() { }
}
}
And the configuration is actually a subsection of my appsettings.json
file, named AzureStorageConfig
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AzureStorageConfig": {
"AccountName": "brazzerswebapp",
"AccountKey": "Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==",
"DefaultEndpointsProtocol": "https",
"EndpointSuffix": "core.windows.net",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
}
}
The only thing I'll add is that, since the constructor has changed, I haven't tested whether something extra needs to be done for it to load appsettings.<environmentname>.json
as opposed to appsettings.json
.
39
Soo cool you work for brazzers!!
– Ivan Juarez
Dec 16 '17 at 19:10
Just a note that you still need to toss .AddJsonFile("yourfile.json") to ConfigConfiguration. IE, you need to tell it where the file is. Didn't see that in the answer.
– Eric
Mar 12 '18 at 17:06
Eric I will retest that, I don't remember adding that line; Could it be necessary only if the name of the json file isn't the default name?
– MDMoore313
Mar 12 '18 at 17:31
Per MSDN, it is not required for ASPNETCORE 2.0, although it doesnt appear to work for me either. docs.microsoft.com/en-us/dotnet/api/…
– Sat Thiru
Mar 26 '18 at 4:47
1
Can you give an example how you inject StorageOptions into your controllers? If I use hug's approach of using dependency injection withpublic HomeController(IOptions<StorageOptions> settings)
, I get this error message: Model bound complex types must not be abstract or value types and must have a parameterless constructor.
– Jpsy
May 3 '18 at 9:21
|
show 2 more comments
For .NET Core 2.0, things have changed a little bit. The startup constructor takes a Configuration object as a parameter, So using the ConfigurationBuilder
is not required. Here is mine:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig"));
}
My POCO is the StorageOptions
object mentioned at the top:
namespace Brazzers.Models
{
public class StorageOptions
{
public String StorageConnectionString { get; set; }
public String AccountName { get; set; }
public String AccountKey { get; set; }
public String DefaultEndpointsProtocol { get; set; }
public String EndpointSuffix { get; set; }
public StorageOptions() { }
}
}
And the configuration is actually a subsection of my appsettings.json
file, named AzureStorageConfig
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AzureStorageConfig": {
"AccountName": "brazzerswebapp",
"AccountKey": "Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==",
"DefaultEndpointsProtocol": "https",
"EndpointSuffix": "core.windows.net",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
}
}
The only thing I'll add is that, since the constructor has changed, I haven't tested whether something extra needs to be done for it to load appsettings.<environmentname>.json
as opposed to appsettings.json
.
39
Soo cool you work for brazzers!!
– Ivan Juarez
Dec 16 '17 at 19:10
Just a note that you still need to toss .AddJsonFile("yourfile.json") to ConfigConfiguration. IE, you need to tell it where the file is. Didn't see that in the answer.
– Eric
Mar 12 '18 at 17:06
Eric I will retest that, I don't remember adding that line; Could it be necessary only if the name of the json file isn't the default name?
– MDMoore313
Mar 12 '18 at 17:31
Per MSDN, it is not required for ASPNETCORE 2.0, although it doesnt appear to work for me either. docs.microsoft.com/en-us/dotnet/api/…
– Sat Thiru
Mar 26 '18 at 4:47
1
Can you give an example how you inject StorageOptions into your controllers? If I use hug's approach of using dependency injection withpublic HomeController(IOptions<StorageOptions> settings)
, I get this error message: Model bound complex types must not be abstract or value types and must have a parameterless constructor.
– Jpsy
May 3 '18 at 9:21
|
show 2 more comments
For .NET Core 2.0, things have changed a little bit. The startup constructor takes a Configuration object as a parameter, So using the ConfigurationBuilder
is not required. Here is mine:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig"));
}
My POCO is the StorageOptions
object mentioned at the top:
namespace Brazzers.Models
{
public class StorageOptions
{
public String StorageConnectionString { get; set; }
public String AccountName { get; set; }
public String AccountKey { get; set; }
public String DefaultEndpointsProtocol { get; set; }
public String EndpointSuffix { get; set; }
public StorageOptions() { }
}
}
And the configuration is actually a subsection of my appsettings.json
file, named AzureStorageConfig
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AzureStorageConfig": {
"AccountName": "brazzerswebapp",
"AccountKey": "Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==",
"DefaultEndpointsProtocol": "https",
"EndpointSuffix": "core.windows.net",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
}
}
The only thing I'll add is that, since the constructor has changed, I haven't tested whether something extra needs to be done for it to load appsettings.<environmentname>.json
as opposed to appsettings.json
.
For .NET Core 2.0, things have changed a little bit. The startup constructor takes a Configuration object as a parameter, So using the ConfigurationBuilder
is not required. Here is mine:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig"));
}
My POCO is the StorageOptions
object mentioned at the top:
namespace Brazzers.Models
{
public class StorageOptions
{
public String StorageConnectionString { get; set; }
public String AccountName { get; set; }
public String AccountKey { get; set; }
public String DefaultEndpointsProtocol { get; set; }
public String EndpointSuffix { get; set; }
public StorageOptions() { }
}
}
And the configuration is actually a subsection of my appsettings.json
file, named AzureStorageConfig
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\mssqllocaldb;",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AzureStorageConfig": {
"AccountName": "brazzerswebapp",
"AccountKey": "Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==",
"DefaultEndpointsProtocol": "https",
"EndpointSuffix": "core.windows.net",
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=brazzerswebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
}
}
The only thing I'll add is that, since the constructor has changed, I haven't tested whether something extra needs to be done for it to load appsettings.<environmentname>.json
as opposed to appsettings.json
.
edited Mar 26 '18 at 9:27
Massimiliano Kraus
2,36941632
2,36941632
answered Nov 19 '17 at 11:45
MDMoore313MDMoore313
1,8911326
1,8911326
39
Soo cool you work for brazzers!!
– Ivan Juarez
Dec 16 '17 at 19:10
Just a note that you still need to toss .AddJsonFile("yourfile.json") to ConfigConfiguration. IE, you need to tell it where the file is. Didn't see that in the answer.
– Eric
Mar 12 '18 at 17:06
Eric I will retest that, I don't remember adding that line; Could it be necessary only if the name of the json file isn't the default name?
– MDMoore313
Mar 12 '18 at 17:31
Per MSDN, it is not required for ASPNETCORE 2.0, although it doesnt appear to work for me either. docs.microsoft.com/en-us/dotnet/api/…
– Sat Thiru
Mar 26 '18 at 4:47
1
Can you give an example how you inject StorageOptions into your controllers? If I use hug's approach of using dependency injection withpublic HomeController(IOptions<StorageOptions> settings)
, I get this error message: Model bound complex types must not be abstract or value types and must have a parameterless constructor.
– Jpsy
May 3 '18 at 9:21
|
show 2 more comments
39
Soo cool you work for brazzers!!
– Ivan Juarez
Dec 16 '17 at 19:10
Just a note that you still need to toss .AddJsonFile("yourfile.json") to ConfigConfiguration. IE, you need to tell it where the file is. Didn't see that in the answer.
– Eric
Mar 12 '18 at 17:06
Eric I will retest that, I don't remember adding that line; Could it be necessary only if the name of the json file isn't the default name?
– MDMoore313
Mar 12 '18 at 17:31
Per MSDN, it is not required for ASPNETCORE 2.0, although it doesnt appear to work for me either. docs.microsoft.com/en-us/dotnet/api/…
– Sat Thiru
Mar 26 '18 at 4:47
1
Can you give an example how you inject StorageOptions into your controllers? If I use hug's approach of using dependency injection withpublic HomeController(IOptions<StorageOptions> settings)
, I get this error message: Model bound complex types must not be abstract or value types and must have a parameterless constructor.
– Jpsy
May 3 '18 at 9:21
39
39
Soo cool you work for brazzers!!
– Ivan Juarez
Dec 16 '17 at 19:10
Soo cool you work for brazzers!!
– Ivan Juarez
Dec 16 '17 at 19:10
Just a note that you still need to toss .AddJsonFile("yourfile.json") to ConfigConfiguration. IE, you need to tell it where the file is. Didn't see that in the answer.
– Eric
Mar 12 '18 at 17:06
Just a note that you still need to toss .AddJsonFile("yourfile.json") to ConfigConfiguration. IE, you need to tell it where the file is. Didn't see that in the answer.
– Eric
Mar 12 '18 at 17:06
Eric I will retest that, I don't remember adding that line; Could it be necessary only if the name of the json file isn't the default name?
– MDMoore313
Mar 12 '18 at 17:31
Eric I will retest that, I don't remember adding that line; Could it be necessary only if the name of the json file isn't the default name?
– MDMoore313
Mar 12 '18 at 17:31
Per MSDN, it is not required for ASPNETCORE 2.0, although it doesnt appear to work for me either. docs.microsoft.com/en-us/dotnet/api/…
– Sat Thiru
Mar 26 '18 at 4:47
Per MSDN, it is not required for ASPNETCORE 2.0, although it doesnt appear to work for me either. docs.microsoft.com/en-us/dotnet/api/…
– Sat Thiru
Mar 26 '18 at 4:47
1
1
Can you give an example how you inject StorageOptions into your controllers? If I use hug's approach of using dependency injection with
public HomeController(IOptions<StorageOptions> settings)
, I get this error message: Model bound complex types must not be abstract or value types and must have a parameterless constructor.– Jpsy
May 3 '18 at 9:21
Can you give an example how you inject StorageOptions into your controllers? If I use hug's approach of using dependency injection with
public HomeController(IOptions<StorageOptions> settings)
, I get this error message: Model bound complex types must not be abstract or value types and must have a parameterless constructor.– Jpsy
May 3 '18 at 9:21
|
show 2 more comments
If you just want to get the value of the token then use
Configuration["AppSettings:token"]
add a comment |
If you just want to get the value of the token then use
Configuration["AppSettings:token"]
add a comment |
If you just want to get the value of the token then use
Configuration["AppSettings:token"]
If you just want to get the value of the token then use
Configuration["AppSettings:token"]
edited Jul 20 '17 at 14:36
answered Jul 3 '17 at 11:59
ManiMani
7261021
7261021
add a comment |
add a comment |
For .NET Core 2.0, you can simply:
Declare your key/value pairs in appsettings.json:
{
"MyKey": "MyValue
}
Inject the configuration service in startup.cs, and get the value using the service
using Microsoft.Extensions.Configuration;
public class Startup
{
public void Configure(IConfiguration configuration,
... other injected services
)
{
app.Run(async (context) =>
{
string myValue = configuration["MyKey"];
await context.Response.WriteAsync(myValue);
});
add a comment |
For .NET Core 2.0, you can simply:
Declare your key/value pairs in appsettings.json:
{
"MyKey": "MyValue
}
Inject the configuration service in startup.cs, and get the value using the service
using Microsoft.Extensions.Configuration;
public class Startup
{
public void Configure(IConfiguration configuration,
... other injected services
)
{
app.Run(async (context) =>
{
string myValue = configuration["MyKey"];
await context.Response.WriteAsync(myValue);
});
add a comment |
For .NET Core 2.0, you can simply:
Declare your key/value pairs in appsettings.json:
{
"MyKey": "MyValue
}
Inject the configuration service in startup.cs, and get the value using the service
using Microsoft.Extensions.Configuration;
public class Startup
{
public void Configure(IConfiguration configuration,
... other injected services
)
{
app.Run(async (context) =>
{
string myValue = configuration["MyKey"];
await context.Response.WriteAsync(myValue);
});
For .NET Core 2.0, you can simply:
Declare your key/value pairs in appsettings.json:
{
"MyKey": "MyValue
}
Inject the configuration service in startup.cs, and get the value using the service
using Microsoft.Extensions.Configuration;
public class Startup
{
public void Configure(IConfiguration configuration,
... other injected services
)
{
app.Run(async (context) =>
{
string myValue = configuration["MyKey"];
await context.Response.WriteAsync(myValue);
});
answered Jun 26 '18 at 22:17
Chris HalcrowChris Halcrow
10.8k46890
10.8k46890
add a comment |
add a comment |
Following works for Console Apps;
1- install following nuget
packages (.csproj
);
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
</ItemGroup>
2- Create appsettings.json
at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".
3- Sample config file:
{
"AppConfig": {
"FilePath": "C:\temp\logs\output.txt"
}
}
4- Program.cs
configurationSection.Key
and configurationSection.Value
will have config properties.
static void Main(string args)
{
try
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
// configurationSection.Key => FilePath
// configurationSection.Value => C:\temp\logs\output.txt
IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
add a comment |
Following works for Console Apps;
1- install following nuget
packages (.csproj
);
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
</ItemGroup>
2- Create appsettings.json
at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".
3- Sample config file:
{
"AppConfig": {
"FilePath": "C:\temp\logs\output.txt"
}
}
4- Program.cs
configurationSection.Key
and configurationSection.Value
will have config properties.
static void Main(string args)
{
try
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
// configurationSection.Key => FilePath
// configurationSection.Value => C:\temp\logs\output.txt
IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
add a comment |
Following works for Console Apps;
1- install following nuget
packages (.csproj
);
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
</ItemGroup>
2- Create appsettings.json
at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".
3- Sample config file:
{
"AppConfig": {
"FilePath": "C:\temp\logs\output.txt"
}
}
4- Program.cs
configurationSection.Key
and configurationSection.Value
will have config properties.
static void Main(string args)
{
try
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
// configurationSection.Key => FilePath
// configurationSection.Value => C:\temp\logs\output.txt
IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
Following works for Console Apps;
1- install following nuget
packages (.csproj
);
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
</ItemGroup>
2- Create appsettings.json
at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".
3- Sample config file:
{
"AppConfig": {
"FilePath": "C:\temp\logs\output.txt"
}
}
4- Program.cs
configurationSection.Key
and configurationSection.Value
will have config properties.
static void Main(string args)
{
try
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
// configurationSection.Key => FilePath
// configurationSection.Value => C:\temp\logs\output.txt
IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
answered Sep 19 '18 at 16:14
Teoman shipahiTeoman shipahi
35.2k87894
35.2k87894
add a comment |
add a comment |
Just to complement the Yuval Itzchakov answer.
You can load configuration without builder function, you can just inject it.
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
add a comment |
Just to complement the Yuval Itzchakov answer.
You can load configuration without builder function, you can just inject it.
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
add a comment |
Just to complement the Yuval Itzchakov answer.
You can load configuration without builder function, you can just inject it.
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
Just to complement the Yuval Itzchakov answer.
You can load configuration without builder function, you can just inject it.
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
answered Apr 14 '18 at 3:30
Tiago BarrosoTiago Barroso
312
312
add a comment |
add a comment |
They just keep changing things – having just updated VS and had the whole project bomb, on the road to recovery and the new way looks like this:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
I kept missing this line!
.SetBasePath(env.ContentRootPath)
1
How can we get the AppSettings values in Test Projects using the same approach?
– S.Siva
Sep 30 '16 at 10:40
add a comment |
They just keep changing things – having just updated VS and had the whole project bomb, on the road to recovery and the new way looks like this:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
I kept missing this line!
.SetBasePath(env.ContentRootPath)
1
How can we get the AppSettings values in Test Projects using the same approach?
– S.Siva
Sep 30 '16 at 10:40
add a comment |
They just keep changing things – having just updated VS and had the whole project bomb, on the road to recovery and the new way looks like this:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
I kept missing this line!
.SetBasePath(env.ContentRootPath)
They just keep changing things – having just updated VS and had the whole project bomb, on the road to recovery and the new way looks like this:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
I kept missing this line!
.SetBasePath(env.ContentRootPath)
edited May 1 '18 at 6:57
Vadim Ovchinnikov
7,00242647
7,00242647
answered Jun 3 '16 at 23:20
MonolithcodeMonolithcode
358117
358117
1
How can we get the AppSettings values in Test Projects using the same approach?
– S.Siva
Sep 30 '16 at 10:40
add a comment |
1
How can we get the AppSettings values in Test Projects using the same approach?
– S.Siva
Sep 30 '16 at 10:40
1
1
How can we get the AppSettings values in Test Projects using the same approach?
– S.Siva
Sep 30 '16 at 10:40
How can we get the AppSettings values in Test Projects using the same approach?
– S.Siva
Sep 30 '16 at 10:40
add a comment |
So I doubt this is good practice but it's working locally, I'll update this if it fails when I publish/deploy (to an IIS web service).
Step 1.) Add this assembly to the top of your class (in my case, controller class):
using Microsoft.Extensions.Configuration;
Step 2.) Add this or something like it:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
Step 3.) Call your key's value by doing this (returns string):
config["NameOfYourKey"]
add a comment |
So I doubt this is good practice but it's working locally, I'll update this if it fails when I publish/deploy (to an IIS web service).
Step 1.) Add this assembly to the top of your class (in my case, controller class):
using Microsoft.Extensions.Configuration;
Step 2.) Add this or something like it:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
Step 3.) Call your key's value by doing this (returns string):
config["NameOfYourKey"]
add a comment |
So I doubt this is good practice but it's working locally, I'll update this if it fails when I publish/deploy (to an IIS web service).
Step 1.) Add this assembly to the top of your class (in my case, controller class):
using Microsoft.Extensions.Configuration;
Step 2.) Add this or something like it:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
Step 3.) Call your key's value by doing this (returns string):
config["NameOfYourKey"]
So I doubt this is good practice but it's working locally, I'll update this if it fails when I publish/deploy (to an IIS web service).
Step 1.) Add this assembly to the top of your class (in my case, controller class):
using Microsoft.Extensions.Configuration;
Step 2.) Add this or something like it:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
Step 3.) Call your key's value by doing this (returns string):
config["NameOfYourKey"]
answered Apr 11 '18 at 1:39
Eric Milliot-MartinezEric Milliot-Martinez
3,06911118
3,06911118
add a comment |
add a comment |
In addition to existing answers I'd like to mention that sometimes it might be useful to have extension methods for IConfiguration
for simplicity's sake.
I keep JWT config in appsettings.json so my extension methods class looks as follows:
public static class ConfigurationExtensions
{
public static string GetIssuerSigningKey(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
return result;
}
public static string GetValidIssuer(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
return result;
}
public static string GetValidAudience(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
return result;
}
public static string GetDefaultPolicy(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Policies:Default");
return result;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
{
var issuerSigningKey = configuration.GetIssuerSigningKey();
var data = Encoding.UTF8.GetBytes(issuerSigningKey);
var result = new SymmetricSecurityKey(data);
return result;
}
public static string GetCorsOrigins(this IConfiguration configuration)
{
string result =
configuration.GetValue<string>("App:CorsOrigins")
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.ToArray();
return result;
}
}
It saves you a lot of lines and you just write clean and minimal code:
...
x.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
ValidAudience = _configuration.GetValidAudience(),
ValidIssuer = _configuration.GetValidIssuer()
};
It's also possible to register IConfiguration
instance as singleton and inject it wherever you need - I use Autofac container here's how you do it:
var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();
You can do the same with MS Dependency Injection:
services.AddSingleton<IConfigurationRoot>(appConfiguration);
add a comment |
In addition to existing answers I'd like to mention that sometimes it might be useful to have extension methods for IConfiguration
for simplicity's sake.
I keep JWT config in appsettings.json so my extension methods class looks as follows:
public static class ConfigurationExtensions
{
public static string GetIssuerSigningKey(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
return result;
}
public static string GetValidIssuer(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
return result;
}
public static string GetValidAudience(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
return result;
}
public static string GetDefaultPolicy(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Policies:Default");
return result;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
{
var issuerSigningKey = configuration.GetIssuerSigningKey();
var data = Encoding.UTF8.GetBytes(issuerSigningKey);
var result = new SymmetricSecurityKey(data);
return result;
}
public static string GetCorsOrigins(this IConfiguration configuration)
{
string result =
configuration.GetValue<string>("App:CorsOrigins")
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.ToArray();
return result;
}
}
It saves you a lot of lines and you just write clean and minimal code:
...
x.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
ValidAudience = _configuration.GetValidAudience(),
ValidIssuer = _configuration.GetValidIssuer()
};
It's also possible to register IConfiguration
instance as singleton and inject it wherever you need - I use Autofac container here's how you do it:
var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();
You can do the same with MS Dependency Injection:
services.AddSingleton<IConfigurationRoot>(appConfiguration);
add a comment |
In addition to existing answers I'd like to mention that sometimes it might be useful to have extension methods for IConfiguration
for simplicity's sake.
I keep JWT config in appsettings.json so my extension methods class looks as follows:
public static class ConfigurationExtensions
{
public static string GetIssuerSigningKey(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
return result;
}
public static string GetValidIssuer(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
return result;
}
public static string GetValidAudience(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
return result;
}
public static string GetDefaultPolicy(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Policies:Default");
return result;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
{
var issuerSigningKey = configuration.GetIssuerSigningKey();
var data = Encoding.UTF8.GetBytes(issuerSigningKey);
var result = new SymmetricSecurityKey(data);
return result;
}
public static string GetCorsOrigins(this IConfiguration configuration)
{
string result =
configuration.GetValue<string>("App:CorsOrigins")
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.ToArray();
return result;
}
}
It saves you a lot of lines and you just write clean and minimal code:
...
x.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
ValidAudience = _configuration.GetValidAudience(),
ValidIssuer = _configuration.GetValidIssuer()
};
It's also possible to register IConfiguration
instance as singleton and inject it wherever you need - I use Autofac container here's how you do it:
var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();
You can do the same with MS Dependency Injection:
services.AddSingleton<IConfigurationRoot>(appConfiguration);
In addition to existing answers I'd like to mention that sometimes it might be useful to have extension methods for IConfiguration
for simplicity's sake.
I keep JWT config in appsettings.json so my extension methods class looks as follows:
public static class ConfigurationExtensions
{
public static string GetIssuerSigningKey(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
return result;
}
public static string GetValidIssuer(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
return result;
}
public static string GetValidAudience(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
return result;
}
public static string GetDefaultPolicy(this IConfiguration configuration)
{
string result = configuration.GetValue<string>("Policies:Default");
return result;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
{
var issuerSigningKey = configuration.GetIssuerSigningKey();
var data = Encoding.UTF8.GetBytes(issuerSigningKey);
var result = new SymmetricSecurityKey(data);
return result;
}
public static string GetCorsOrigins(this IConfiguration configuration)
{
string result =
configuration.GetValue<string>("App:CorsOrigins")
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.ToArray();
return result;
}
}
It saves you a lot of lines and you just write clean and minimal code:
...
x.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
ValidAudience = _configuration.GetValidAudience(),
ValidIssuer = _configuration.GetValidIssuer()
};
It's also possible to register IConfiguration
instance as singleton and inject it wherever you need - I use Autofac container here's how you do it:
var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();
You can do the same with MS Dependency Injection:
services.AddSingleton<IConfigurationRoot>(appConfiguration);
answered Oct 20 '18 at 7:02
Alex HermanAlex Herman
694716
694716
add a comment |
add a comment |
Was this "cheating"? I just made my Configuration in the Startup class static, and then I can access it from anywhere else:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public static IConfiguration Configuration { get; set; }
add a comment |
Was this "cheating"? I just made my Configuration in the Startup class static, and then I can access it from anywhere else:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public static IConfiguration Configuration { get; set; }
add a comment |
Was this "cheating"? I just made my Configuration in the Startup class static, and then I can access it from anywhere else:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public static IConfiguration Configuration { get; set; }
Was this "cheating"? I just made my Configuration in the Startup class static, and then I can access it from anywhere else:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public static IConfiguration Configuration { get; set; }
answered Jul 25 '18 at 21:43
Brian MooreBrian Moore
112
112
add a comment |
add a comment |
protected by Yuval Itzchakov Feb 3 at 5:27
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
possible duplicate of ASP.NET 5 (vNext) - Getting a Configuration Setting
– mason
Jul 16 '15 at 13:20
A reference MSDN that provides additional insight.
– MDMoore313
Nov 18 '17 at 22:06
this can be even simplified just by using dependency injection of IConfiguration (in .net core 2.0). Which is explained here coding-issues.com/2018/10/…
– Ranadheer Reddy
Oct 9 '18 at 14:27