简体   繁体   中英

.Net Core Configuration.GetSection().Get<>() not binding

I'm Trying to Inject my settings from appsettings.json into an Object, i'm following microsoft documentation and my Configuration.GetSection().Get<>() is always null, the documentation that i am using is this one Documentation

I am using .Net Core 2.1

My setting is this:

{
  "MongoSettings": {
    "ConnectionString": "mongodb://admin:abc123!@localhost",
    "Database": "NotesDb"
  }
}

My class to inject is this one:

public class MongoSettings
{
    public string ConnectionString;
    public string Database;
}

and i'm using the following code to fill my injection and it comes always null.

Configuration.GetSection("MongoSettings").Get<MongoSettings>()

Below is the return that i am getting when i'm using the code

在此输入图像描述

My Configuration is ok, look the image below.

在此输入图像描述

What am i doing wrong to my object comes with ConnectionString and Database null? Can someone help me?

Your class is 2 fields. The configuration system only works with properties. Add { get; set; } { get; set; } { get; set; } to the end of both of the fields to fix it.

public class MongoSettings
{
    public string ConnectionString { get; set; }
    public string Database { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM