How to read AppSettings values ​​from .json file in ASP.NET Core

I set my AppSettings data in appsettings / Config.json as follows:

{ "AppSettings": { "token": "1234" } } 

I searched online for how to read AppSettings values ​​from a .json file, but I could not get anything useful.

I did my best:

 var configuration = new Configuration(); var appSettings = configuration.Get("AppSettings"); // null var token = configuration.Get("token"); // null 

I know that with ASP.NET 4.0 you can do this:

 System.Configuration.ConfigurationManager.AppSettings["token"]; 

But how to do it in ASP.NET Core?

+187
c # asp.net-core .net-core
Jul 16 '15 at 11:57
source share
16 answers

It had a few twists and turns. I modified this answer to keep up to date with ASP.NET Core 2.0 (as of 02/26/2018).

This is mainly taken from official documentation :

To work with the settings in your ASP.NET application, it is recommended that you only create an instance of Configuration in your Startup class applications. Then use the Options template to access individual settings. 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 create 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 appsettings.{Environment}.json for each environment, if necessary.

If we want to enter our configuration into our controllers, we will need to register it at runtime. We do this through 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 introduce 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); } 

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")); } } 
+261
Jul 16 '15 at 12:05
source share

First: assembly name and namespace Microsoft.Framework.ConfigurationModel changed to Microsoft.Framework.Configuration. Therefore you should use: eg

 "Microsoft.Framework.Configuration.Json": "1.0.0-beta7" 

as a dependency in project.json . Use beta5 or 6 if you do not have 7 installed. Then you can do something similar 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 want to get a variable from 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 as follows:

 public class AppSettings { public string token { get; set; } } 

and configure the following services:

 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.Configure<MvcOptions>(options => { //mvc options }); services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); } 

and then access it, for example, to the controller:

 public class HomeController : Controller { private string _token; public HomeController(IOptions<AppSettings> settings) { _token = settings.Options.token; } } 
+58
23 sept. '15 at 15:27
source share

For .NET Core 2.0, things have changed a bit. The launch constructor accepts the configuration object as a parameter, so using ConfigurationBuilder not required. Here is my:

 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 called 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 will add is that since the constructor has changed, I have not tested whether I need to do something extra to load appsettings.<environmentname>.json and not appsettings.json .

+44
Nov 19 '17 at 11:45
source share

If you just want to get the value of the token, use

Configuration["AppSettings:token"]

+20
Jul 03 '17 at 11:59 on
source share

With Core 2.2, and in the easiest way ...

 public IActionResult Index([FromServices] IConfiguration config) { var myValue = config.GetValue<string>("MyKey"); } 

appsettings.json automatically loaded and accessible through any of the constructor or injection actions, and there GetSection method on IConfiguration a. No need to modify Startup.cs or Program.cs if you only need appsettings.json .

+16
Apr 22 '19 at 21:12
source share

The following works for console applications;

1- install the 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 the root level. Right-click on it and "Copy to output directory" as " Copy if new ."

3- Example configuration file:

 { "AppConfig": { "FilePath": "C:\\temp\\logs\\output.txt" } } 

4- Program.cs

configurationSection.Key and configurationSection.Value will have configuration 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); } } 
+10
Sep 19 '18 at 16:14
source share

Just to complement Yuval Itchakov’s answer.

You can load the configuration without the builder function, you can just enter it.

 public IConfiguration Configuration { get; set; } public Startup(IConfiguration configuration) { Configuration = configuration; } 
+7
Apr 14 '18 at 3:30
source share

For .NET Core 2.0, you can simply:

Declare your key / value pairs in appsettings.json:

 { "MyKey": "MyValue" } 

Insert 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); }); 
+7
Jun 26 '18 at 22:17
source share

I doubt this is a good practice, but it works locally. I will update this if publishing / deployment fails (for IIS Web Service).

Step 1 - Add this assembly to the top of your class (in my case, the controller class):

 using Microsoft.Extensions.Configuration; 

Step 2 - Add this or something like this:

 var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json").Build(); 

Step 3 - Call the key value by doing this (returns a string):

 config["NameOfYourKey"] 
+6
Apr 11 '18 at 1:39
source share

In addition to the existing answers, I would like to mention that it would sometimes be useful to have extension methods for IConfiguration for simplicity.

I save the JWT configuration in appsettings.json, so the extension method class looks like this:

 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; } } 

This 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 is also possible to register an instance of IConfiguration as a singleton and enter it where you need it - I use the Autofac container here, as 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); 
+6
Oct 20 '18 at 7:02
source share

They just keep changing things - they just updated VS and possessed the entire bomb of the project, on their way 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 skipping this line!

 .SetBasePath(env.ContentRootPath) 
+5
Jun 03 '16 at 23:20
source share

Here is a complete example of using ASP.NET Core!

articles.json

 { "shownArticlesCount": 3, "articles": [ { "title": "My Title 1", "thumbnailLink": "example.com/img1.png", "authorProfileLink": "example.com/@@alper", "authorName": "Alper Ebicoglu", "publishDate": "2018-04-17", "text": "...", "link": "..." }, { "title": "My Title 2", "thumbnailLink": "example.com/img2.png", "authorProfileLink": "example.com/@@alper", "authorName": "Alper Ebicoglu", "publishDate": "2018-04-17", "text": "...", "link": "..." }, ] } 



ArticleContainer.cs

 public class ArticleContainer { public int ShownArticlesCount { get; set; } public List<Article> Articles { get; set; } } public class Article { public string Title { get; set; } public string ThumbnailLink { get; set; } public string AuthorName { get; set; } public string AuthorProfileLink { get; set; } public DateTime PublishDate { get; set; } public string Text { get; set; } public string Link { get; set; } } 



Startup.cs

 public class Startup { public IConfigurationRoot ArticleConfiguration { get; set; } public Startup(IHostingEnvironment env) { ArticleConfiguration = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("articles.json") .Build(); } public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure<ArticleContainer>(ArticleConfiguration); } } 



Index.cshtml.cs

 public class IndexModel : PageModel { public ArticleContainer ArticleContainer { get;set; } private readonly IOptions<ArticleContainer> _articleContainer; public IndexModel(IOptions<ArticleContainer> articleContainer) { _articleContainer = articleContainer; } public void OnGet() { ArticleContainer = _articleContainer.Value; } } 



Index.cshtml.cs

 <h1>@Model.ArticleContainer.ShownArticlesCount</h1> 
+4
Feb 19 '19 at 8:05
source share

You can try below code. it works for me.

 public class Settings { private static IHttpContextAccessor _HttpContextAccessor; public Settings(IHttpContextAccessor httpContextAccessor) { _HttpContextAccessor = httpContextAccessor; } public static void Configure(IHttpContextAccessor httpContextAccessor) { _HttpContextAccessor = httpContextAccessor; } public static IConfigurationBuilder Getbuilder() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); return builder; } public static string GetAppSetting(string key) { //return Convert.ToString(ConfigurationManager.AppSettings[key]); var builder = Getbuilder(); var GetAppStringData = builder.Build().GetValue<string>("AppSettings:" + key); return GetAppStringData; } public static string GetConnectionString(string key="DefaultName") { var builder = Getbuilder(); var ConnectionString = builder.Build().GetValue<string>("ConnectionStrings:"+key); return ConnectionString; } } 

Here I created one class to get the connection string and application settings.

In the Startup.cs file, you need to register the class as shown below.

 public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>(); Settings.Configure(httpContextAccessor); } } 
+2
Jun 27 '19 at 12:47 on
source share

Was it a "trick"? I just installed my configuration in start starts, and then I can access it from another place:

 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; } 
+1
Jul 25 '18 at 21:43
source share

Get it inside the controller as an object by calling Get<YourType>()

public IActionResult Index([FromServices] IConfiguration config) { BillModel model= config.GetSection("Yst.Requisites").Get<BillModel>(); return View(model); }

+1
Jun 21. '19 at 8:05
source share

.NET Core 2.1.0

  1. Create a .json file in the root directory
  2. In your code:
 var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); 
 var config = builder.Build(); 

3. Install the following dependencies:

 Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.json 

4. Then IMPORTANT: Right-click the appsettings.json file → click Properties → select Copy, if newer: enter image description here

  1. Finally you can do:

    config ["key1"]

Given that my configuration file will look like this:

 { "ConnectionStrings": "myconnection string here", "key1": "value here" } 
+1
Sep 13 '19 at 10:46
source share



All Articles