I have the following config in my appsettings.json File
{
"AppSettings": {
"MainUser": {
"Name": "Urs",
"Surname": "Barandun",
"SesstionTimeInMin": "30",
}
},
And I'd like to create a custom configuration class and bind it. Eg:
MainUserConfiguration mainUserConfiguration = new MainUserConfiguration();
var configSection = config.GetSection("MainUserConfiguration");
configSection.Bind(mainUserConfiguration);
But, my code does not work. :/
Based on what you've provided, your appsettings file and the nested JSON for your configuration don't match up. A typical ASP.NET Core appsettings.json doesn't have a nested element called "AppSettings", and further you're getting a configuration section called "MainUserConfiguration" while your actual JSON just names that section "MainUser".
appsettings example:
{
"MyFirstClass": {
"Option1": "some string value",
"Option2": 42
},
"MySecondClass": {
"SettingOne": "some string value",
"SettingTwo": 42
}
}
In your code:
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; }
}
In your Startup.cs (presuming that's where you're accessing it with a defined Configuration object:
var myFirstClass = Configuration.GetSection("MyFirstClass").Get<MyFirstClass>();
var mySecondClass = Configuration.GetSection("MySecondClass").Get<MySecondClass>();
Console.WriteLine($"The answer is always {myFirstClass.Option2}");
Related
In C# we can bind some settings in appSettings to class, for example like that:
var connectionStrings = new ConnectionStrings();
var sectionConnectionString = Configuration.GetSection("ConnectionStrings");
In appsettings it looks like below:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
And when I want to bind Logging I need to call another bind:
Configuration.GetSection("Logging");
How can I bind whole appsettings file? GetSection with empty string doesn't work:
Configuration.GetSection("");
You need a Class for your config and afterwards you can use this (You do not need to map every setting, just the ones you need):
var configObject = Configuration.Get<ConfigObject>();
Example config object:
public class ConfigObject {
public Logging Logging { get; set; }
public string AllowedHosts { get; set; }
public ConnectionStrings ConnectionStrings { get; set; }
}
public class Logging {
public LogLevel LogLevel { get; set; }
}
public class LogLevel {
public string Default { get; set; }
}
public class ConnectionStrings {
public string ConnString1 { get; set; }
}
Hint:
if you're not using aspnetcore you probably need to also include this NuGet package: Microsoft.Extensions.Configuration.Binder
You can use the Configuration instance as it is.
You can bind the settings to a class:
var appSettings = Configuration.Get<AppSettings>();
Or you can inject the settings with the Options pattern
services.Configure<AppSettings>(Configuration);
Microsoft.Extensions.Configuration has its own API for navigating through the JSON contained in the config file it reads in. (This is what ASP.NET uses for configuration)
For a given JSON node- is there a way to get access to its contents as a string rather than as more Configuration objects? I have JSON objects in my config file which I need to run through a JSON deserializer (so I just want to read this node from the file as a string).
Something akin to the following:
var myObjectsSection = configuration.GetSection("MyObjects");
var innerText = myObjectsSection.InnerText; //Is there any way to do this???
var myObjs = JsonConvert.DeserializeObject<MyObject[]>(innerText);
Config file:
{
"SomeSetting": "mySetting",
"MyObjects": [
{
...
},
{
...
}
]
}
Asp.net core 3 has a method for getting type-related configuration value: T IConfigurationSection.Get<T>()
I've tried to parse the custom configuration which you described and it is working.
appsetting.json:
{
"CustomSection": [
{
"SomeProperty": 1,
"SomeOtherProperty": "value1"
}
]
}
Startup class:
public class Startup
{
public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
IConfigurationSection section = this.Configuration.GetSection("CustomSection");
var configs = section.Get<List<CustomSectionClass>>();
}
public class CustomSectionClass
{
public int SomeProperty { get; set; }
public string SomeOtherProperty { get; set; }
}
}
I try to get my section from appsettings.json, and then bind it to the intance of MongoSettings class, but I have an exception which is:
"Cannot create instance of type 'System.String' because it is missing
a public parameterless constructor."
It is strange, because I'm using the same method to get jwt settings.
Please take a look:
var jwtSettings = Configuration.GetSection("jwt").Get<JwtSettings>(); //it works
var mongoSettings = Configuration.GetSection("mongo").Get<MongoSettings>(); //it doesn't
appsettings.json
"Jwt": {
"issuer" : "localhost:5000",
"expiryMinutes" : 60,
"key" : "das##4SD120847#12313"
},
"Mongo": {
"connection:" : "mongodb://localhost:27017",
"database" : "MemoTime"
}
MongoSettings:
public class MongoSettings
{
public string Connection { get; set; }
public string Database { get; set; }
}
JwtSettings:
public class JwtSettings
{
public string Key { get; set; }
public string ValidIssuer { get; set; }
public int ExpiryMinutes { get; set; }
}
As you can see, both clasess and sections in app settings looks similarly, so why getting settings for mongo does not work?
You Issue is in Json there is extra colon ":" that why it is giving error
Valid Json Data.
"Jwt":
{
"issuer": "localhost:5000",
"expiryMinutes": 60,
"key": "das##4SD120847#12313"
},
"Mongo":
{
"connection": "mongodb://localhost:27017",
"database": "MemoTime"
}
Is there any way to edit value inside appsetting.json using controller?
So, here is the appsetting.json:
{
"Person": {
"p1": "test1",
"p2": "test2",
"p3": "test3"
}
}
and this is the class:
public class
{
public string p1{ get; set; }
public string p2{ get; set; }
public string p3{ get; set; }
}
I do some research but no clue. I just find how to read the value of appsetting.json. What I want is to edit the value from controller and save it.
Try
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["p1"].Value = "test1";
config.AppSettings.Settings["p2"].Value = "test2";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
I started some basic project on .net Core 1.1,
and I wish to map some properties from appsettings.json to object, but I probably can't understand correct name convention or something pretty basic
Regarding MSDN Using Options and configuration objects section,
it is very easy to use it.
I added next lines to appsettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"XXXOptions": {
"X1": {
"AppId": "11",
"AppCode": "22"
},
"X2": {
"AppId": "",
"AppCode": ""
}
}
}
I added custom class
public class XXXOptions
{
public XXXOptions()
{
}
public X1 X1{ get; set; }
public X2 X2{ get; set; }
}
public class X1
{
public int AppId { get; set; }
public int AppCode { get; set; }
}
public class X2
{
public int AppId { get; set; }
public int AppCode { get; set; }
}
I added next code to Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Adds services required for using options.
services.AddOptions();
// Register the IConfiguration instance which MyOptions binds against.
services.Configure<XXXOptions>(Configuration);
// Add framework services.
services.AddMvc();
}
public class XXXController : Controller
{
private readonly XXXOptions _options;
public XXXController(IOptions<XXXOptions> optionsAccessor)
{
_options = optionsAccessor.Value;
}
public IActionResult Index()
{
var option1 = _options.X1;
return Content($"option1 = {option1.AppCode}, option2 = {option1.AppId}");
return View();
}
}
optionsAccessor.Value - Value containes null values at XXXController constructor.
but it seems like framework show mappet values at JsonConfigurationProvider inside of Configuration property
any ideas?
In ConfigureServices method change:
services.Configure<XXXOptions>(Configuration);
to
services.Configure<XXXOptions>(Configuration.GetSection("XXXOptions"));