how to get value from appsettings.json

前端 未结 6 669
时光说笑
时光说笑 2020-12-07 12:34
public class Bar
{
    public static readonly string Foo = ConfigurationManager.AppSettings[\"Foo\"];
}

In the .NET Framework 4.x, I can use the

相关标签:
6条回答
  • 2020-12-07 12:38

    The solutions on top are time consuming and not straightforward, this is the best effective way to do it, no setup needed on startup or anything. It's like using the good ol Configuration.Manager.AppSettings["setting"]

    First create a class like "Credential":

    public class Credential
      {
          public string Username {get;set}
          public string Password {get;set;}
      }
    

    Now that's setup let put the IConfiguration on your constructor like so:

        private IConfiguration _configuration;
        public ValuesController(IConfiguration iconfig)
        {
            _configuration = iconfig;
        }
    

    Then you're ready to call it!

        Credential c = new Credential();
        c.UserName = _configuration.GetValue<string>("Credential:username");
        c.Password = _configuration.GetValue<string>("Credential:password");
    

    Assuming your appsettings.json looks like this:

    "Credential": {
        "username": "myuser",
        "password": "mypassword"
      }
    

    Hope this helps somebody.

    0 讨论(0)
  • 2020-12-07 12:40

    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/

    0 讨论(0)
  • 2020-12-07 12:42
    1. Add this in AppSettings.json file
      "Swagger": { "Title": "API DEVELOPMENT" }

    2. Then configure that in Startup.cs file

      public Startup(IConfiguration configuration)
      {
          Configuration = configuration;
      }
      
      public IConfiguration Configuration { get; }
      
    3. Next get the value from appsettings.json

      var title = Configuration.GetSection("Swagger:Title").Value;
      
    4. Finally put here

      services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = title, Version = "v1" }); }
      
    0 讨论(0)
  • 2020-12-07 12:52

    define your class as

    public class MyClass{
       private readonly IConfiguration _configuration;
       public MyClass(IConfiguration configuration)
            {
                _configuration = configuration;
            }
       public void myFunction(){
           var value= _configuration.GetValue("xxx");
    }
    }
    

    when you call it from anywhere else

    IConfiguration config = new ConfigurationBuilder()
                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false).Build();
    MyClass myclass = new MyClass(config)
    
    0 讨论(0)
  • 2020-12-07 12:54

    Addition to answer from @MindingData. I like to map my settings recursively using Configuration.Bind(settings); so that I don't have to add every new section in ConfigureServices.

    Example:

    appsettings.json:

    {
        "MyConfiguration": {
            "MyProperty": true 
        }
    }
    

    Settings class, properties must match appsettings.json names:

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

    Startup.cs

    public class Startup
    {
        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)
        {
    
            var settings = new Settings();
            Configuration.Bind(settings);
            services.AddSingleton(settings);
            ...
    

    Can be used in controllers like this:

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly Settings _settings;
    
        public ValuesController(Settings settings)
        {
            _settings = settings;
        }
    
        [HttpGet("GetValue")]
        public ActionResult<string> Get()
        {
            return Ok(_settings.MyConfiguration.MyProperty);
        }
    }
    
    0 讨论(0)
  • 2020-12-07 12:55

    You can also use the configuration directly. Your settings are injected so you can get to them with DI...

    private readonly IConfiguration _configuration;
    
    public MyClass(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    

    and then you can read your settings...

    In this case I'm getting a collection back...

    var myList = _configuration.GetSection("MyList").Get<List<string>>();
    
    0 讨论(0)
提交回复
热议问题