Getting Value from Appsettings.JSON in .Net Core

Getting value from appsettings.json in .net core

Program and Startup class

.NET Core 2.x

You don't need to new IConfiguration in the Startup constructor. Its implementation will be injected by the DI system.

// Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}

// Startup.cs
public class Startup
{
public IHostingEnvironment HostingEnvironment { get; private set; }
public IConfiguration Configuration { get; private set; }

public Startup(IConfiguration configuration, IHostingEnvironment env)
{
this.HostingEnvironment = env;
this.Configuration = configuration;
}
}

.NET Core 1.x

You need to tell Startup to load the appsettings files.

// Program.cs
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();

host.Run();
}
}

//Startup.cs
public class Startup
{
public IConfigurationRoot Configuration { get; private set; }

public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();

this.Configuration = builder.Build();
}
...
}


Getting Values

There are many ways you can get the value you configure from the app settings:

  • Simple way using ConfigurationBuilder.GetValue<T>
  • Using Options Pattern

Let's say your appsettings.json looks like this:

{
"ConnectionStrings": {
...
},
"AppIdentitySettings": {
"User": {
"RequireUniqueEmail": true
},
"Password": {
"RequiredLength": 6,
"RequireLowercase": true,
"RequireUppercase": true,
"RequireDigit": true,
"RequireNonAlphanumeric": true
},
"Lockout": {
"AllowedForNewUsers": true,
"DefaultLockoutTimeSpanInMins": 30,
"MaxFailedAccessAttempts": 5
}
},
"Recaptcha": {
...
},
...
}

Simple Way

You can inject the whole configuration into the constructor of your controller/class (via IConfiguration) and get the value you want with a specified key:

public class AccountController : Controller
{
private readonly IConfiguration _config;

public AccountController(IConfiguration config)
{
_config = config;
}

[AllowAnonymous]
public IActionResult ResetPassword(int userId, string code)
{
var vm = new ResetPasswordViewModel
{
PasswordRequiredLength = _config.GetValue<int>(
"AppIdentitySettings:Password:RequiredLength"),
RequireUppercase = _config.GetValue<bool>(
"AppIdentitySettings:Password:RequireUppercase")
};

return View(vm);
}
}

Options Pattern

The ConfigurationBuilder.GetValue<T> works great if you only need one or two values from the app settings. But if you want to get multiple values from the app settings, or you don't want to hard code those key strings in multiple places, it might be easier to use Options Pattern. The options pattern uses classes to represent the hierarchy/structure.

To use options pattern:

  1. Define classes to represent the structure
  2. Register the configuration instance which those classes bind against
  3. Inject IOptions<T> into the constructor of the controller/class you want to get values on

1. Define configuration classes to represent the structure

You can define classes with properties that need to exactly match the keys in your app settings. The name of the class does't have to match the name of the section in the app settings:

public class AppIdentitySettings
{
public UserSettings User { get; set; }
public PasswordSettings Password { get; set; }
public LockoutSettings Lockout { get; set; }
}

public class UserSettings
{
public bool RequireUniqueEmail { get; set; }
}

public class PasswordSettings
{
public int RequiredLength { get; set; }
public bool RequireLowercase { get; set; }
public bool RequireUppercase { get; set; }
public bool RequireDigit { get; set; }
public bool RequireNonAlphanumeric { get; set; }
}

public class LockoutSettings
{
public bool AllowedForNewUsers { get; set; }
public int DefaultLockoutTimeSpanInMins { get; set; }
public int MaxFailedAccessAttempts { get; set; }
}

2. Register the configuration instance

And then you need to register this configuration instance in ConfigureServices() in the start up:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
...

namespace DL.SO.UI.Web
{
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
var identitySettingsSection =
_configuration.GetSection("AppIdentitySettings");
services.Configure<AppIdentitySettings>(identitySettingsSection);
...
}
...
}
}

3. Inject IOptions

Lastly on the controller/class you want to get the values, you need to inject IOptions<AppIdentitySettings> through constructor:

public class AccountController : Controller
{
private readonly AppIdentitySettings _appIdentitySettings;

public AccountController(IOptions<AppIdentitySettings> appIdentitySettingsAccessor)
{
_appIdentitySettings = appIdentitySettingsAccessor.Value;
}

[AllowAnonymous]
public IActionResult ResetPassword(int userId, string code)
{
var vm = new ResetPasswordViewModel
{
PasswordRequiredLength = _appIdentitySettings.Password.RequiredLength,
RequireUppercase = _appIdentitySettings.Password.RequireUppercase
};

return View(vm);
}
}

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

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

how to get value from appsettings.json

So there are really two ways to go about this.

Option 1 : Options Class

You have an appsettings.json file :

{
"myConfiguration": {
"myProperty": true
}
}

You create a Configuration POCO like so :

public class MyConfiguration
{
public bool MyProperty { get; set; }
}

In your startup.cs you have something in your ConfigureServices that registers the configuration :

public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyConfiguration>(Configuration.GetSection("myConfiguration"));
}

Then in your controller/service you inject in the IOptions and it's useable.

public class ValuesController : Controller
{
private readonly MyConfiguration _myConfiguration;

public ValuesController(IOptions<MyConfiguration> myConfiguration)
{
_myConfiguration = myConfiguration.Value;
}
}

Personally I don't like using IOptions because I think it drags along some extra junk that I don't really want, but you can do cool things like hot swapping and stuff with it.

Option 2 : Configuration POCO

It's mostly the same but in your Configure Services method you instead bind to a singleton of your POCO.

public void ConfigureServices(IServiceCollection services)
{
//services.Configure<MyConfiguration>(Configuration.GetSection("myConfiguration"));
services.AddSingleton(Configuration.GetSection("myConfiguration").Get<MyConfiguration>());
}

And then you can just inject the POCO directly :

public class ValuesController : Controller
{
private readonly MyConfiguration _myConfiguration;

public ValuesController(MyConfiguration myConfiguration)
{
_myConfiguration = myConfiguration;
}
}

A little simplistic because you should probably use an interface to make unit testing a bit easier but you get the idea.

Mostly taken from here : http://dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/

Show appsettings.json value in cshtml file in .NET Core

Here is a demo to show value from appsettings.json in view:

appsettings.json:

{
...
"Test": {
"TestValue": "testValue"

}
}

view:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
@Configuration.GetSection("Test")["TestValue"]

Get values from appsettings.json in .net core 3.1

In your appsettings.json myKey is inside an AppSettings object.

That whole object is being loaded, so you'll need to reference it:

var myValue = config["AppSettings:myKey"];

Reference: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#hierarchical-configuration-data

How to get values from appsettings.json in a console application using .NET Core?

Your example is mixing in some ASP NET Core approaches that expect your code to be hosted. To minimally solve the issue of getting options or settings from a JSON configuration, consider the following:

A config.json file, set to "Copy to Output Directory" so that it is included with the build:

{
"MyFirstClass": {
"Option1": "some string value",
"Option2": 42
},
"MySecondClass": {
"SettingOne": "some string value",
"SettingTwo": 42
}
}

The following approach will load the content from the JSON file, then bind the content to two strongly-typed options/settings classes, which can be a lot cleaner than going value-by-value:

using System;
using System.IO;
using Microsoft.Extensions.Configuration;

// NuGet packages:
// Microsoft.Extensions.Configuration.Binder
// Microsoft.Extensions.Configuration.Json

namespace SampleConsole
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json", optional: false);

IConfiguration config = builder.Build();

var myFirstClass = config.GetSection("MyFirstClass").Get<MyFirstClass>();
var mySecondClass = config.GetSection("MySecondClass").Get<MySecondClass>();
Console.WriteLine($"The answer is always {myFirstClass.Option2}");
}
}

public class MyFirstClass
{
public string Option1 { get; set; }
public int Option2 { get; set; }
}

public class MySecondClass
{
public string SettingOne { get; set; }
public int SettingTwo { get; set; }
}
}

Get Value from appsetting.json in class

There really is no need to be passing IConfiguration around. The framework already has built in features that allow you to bind an object model from values in setting

Create a simple class to hold your configuration.

public class MyConfig {
public string BaseMediaUrl { get; set; }
public string FolderAnnouncement { get; set; }
}

Setup your class in ConfigureServices in Startup.

//bind object model from configuration
MyConfig myConfig = Configuration.GetSection("MyConfig").Get<MyConfig>();

//add it to services
services.AddSingleton(myConfig);

And inject your strongly typed configuration class where it is needed

private readonly MyConfig conf;

//Constructor
public AnnouncementService(MyConfig config) {
this.conf = config;
}

private async Task<string> SaveAnnouncement(IFormFile file = null, string base64 = null) {
string path = conf.FolderAnnouncement;
string imageUrl = Guid.NewGuid().ToString();
var mediaPath = conf.BaseMediaUrl;
string extension = Path.GetExtension(file.FileName);
var imagePath = mediaPath + path + imageUrl+extension;
if (!string.IsNullOrEmpty(base64)) {
byte[] bytes = Convert.FromBase64String(base64);
File.WriteAllBytes(imagePath, bytes);
} else {
using (var fileStream = new FileStream(imagePath, FileMode.Create)) {
await file.CopyToAsync(fileStream);
}
}
return imageUrl+extension;
}

Note how the magic strings are no longer needed. You can access the desired configuration values via the properties.

Reference Configuration in ASP.NET Core

How to get value from appsettings.json in Program class in asp.net core console application

In the file appsettings.json, you can define Url property like this:

{
"Url": "https://example.com"
}

In the file Program.cs, inside Main method, you can access that property via ConfigureLogging extension method:

public class Program
{
public static void Main(string[] args)
{
var builder = CreateHostBuilder(args);

builder.ConfigureLogging((context, builder) => {
// "https://example.com"
string url = context.Configuration["Url"];

// do stuff...
}).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = null;
});
});
}

Update:

If you want to get the property value via UseKestrel extension method, you can assign it directly, no need to store in the field.

Because you will lose that value when the extension method finish (Url will become null outside the extension method)

public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseKestrel((context, options) =>
{
options.Limits.MaxRequestBodySize = null;

// "192.168.1.4"
string url = context.Configuration["Url"];
var ipAddress = System.Net.IPAddress.Parse(url);
});
});
}

Screenshot:

1

How to read values from appsettings.json inside a class in .Net 6?

var JwtLoginTokenValidationDurationMinutes = builder.Configuration.GetSection("Configurations:JwtLoginTokenValidationDurationMinutes").Value;


Related Topics



Leave a reply



Submit