How do I access Configuration in any class in ASP.NET Core?

前端 未结 11 1683
梦如初夏
梦如初夏 2020-11-29 01:09

I have gone through configuration documentation on ASP.NET core. Documentation says you can access configuration from anywhere in the application.

Below is Startup.c

相关标签:
11条回答
  • 2020-11-29 01:27

    In ASP.NET Core, there are configuration providers for reading configurations from almost anywhere such as files e.g. JSON, INI or XML, environment variables, Azure key vault, command-line arguments, etc. and many more sources. I have written a step by step guide to show you how can you configure your application settings in various files such as JSON, INI or XML and how can you read those settings from your application code. I will also demonstrate how can you read application settings as custom .NET types (classes) and how can you use the built-in ASP.NET Core dependency injection to read your configuration settings in multiple classes, services or even projects available in your solution.

    Read A Step by Step Guide for ASP.NET Core Configuration

    0 讨论(0)
  • 2020-11-29 01:32

    I'm doing it like this at the moment:

    // Requires NuGet package Microsoft.Extensions.Configuration.Json
    
    using Microsoft.Extensions.Configuration;
    using System.IO;
    
    namespace ImagesToMssql.AppsettingsJson
    {
        public static class AppSettingsJson
        {           
            public static IConfigurationRoot GetAppSettings()
            {
                string applicationExeDirectory = ApplicationExeDirectory();
    
                var builder = new ConfigurationBuilder()
                .SetBasePath(applicationExeDirectory)
                .AddJsonFile("appsettings.json");
    
                return builder.Build();
            }
    
            private static string ApplicationExeDirectory()
            {
                var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
                var appRoot = Path.GetDirectoryName(location);
    
                return appRoot;
            }
        }
    }
    

    And then I use this where I need to get the data from the appsettings.json file:

    var appSettingsJson = AppSettingsJson.GetAppSettings();
    // appSettingsJson["keyName"]
    
    0 讨论(0)
  • 2020-11-29 01:33

    I know there may be several ways to do this, I'm using Core 3.1 and was looking for the optimal/cleaner option and I ended up doing this:

    1. My startup class is as default
    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.AddControllers();
    }
    
    1. My appsettings.json is like this
    {
      "CompanySettings": {
        "name": "Fake Co"
      }
    }
    
    
    1. My class is an API Controller, so first I added the using reference and then injected the IConfiguration interface
    using Microsoft.Extensions.Configuration;
    
    public class EmployeeController 
    {
        private IConfiguration _configuration;
        public EmployeeController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
    }
    
    1. Finally I used the GetValue method
    public async Task<IActionResult> Post([FromBody] EmployeeModel form)
    {
        var companyName = configuration.GetValue<string>("CompanySettings:name");
        // companyName = "Fake Co"
    }
    
    0 讨论(0)
  • 2020-11-29 01:37

    I looked into the options pattern sample and saw this:

    public class Startup
    {
        public Startup(IConfiguration config)
        {
            // Configuration from appsettings.json has already been loaded by
            // CreateDefaultBuilder on WebHost in Program.cs. Use DI to load
            // the configuration into the Configuration property.
            Configuration = config;
        }
    ...
    }
    

    When adding Iconfiguration in the constructor of my class, I could access the configuration options through DI.

    Example:

    public class MyClass{
    
        private Iconfiguration _config;
    
        public MyClass(Iconfiguration config){
            _config = config;
        }
    
        ... // access _config["myAppSetting"] anywhere in this class
    }
    
    0 讨论(0)
  • 2020-11-29 01:44

    In 8-2017 Microsoft came out with System.Configuration for .NET CORE v4.4. Currently v4.5 and v4.6 preview.

    For those of us, who works on transformation from .Net Framework to CORE, this is essential. It allows to keep and use current app.config files, which can be accessed from any assembly. It is probably even can be an alternative to appsettings.json, since Microsoft realized the need for it. It works same as before in FW. There is one difference:

    In the web applications, [e.g. ASP.NET CORE WEB API] you need to use app.config and not web.config for your appSettings or configurationSection. You might need to use web.config but only if you deploying your site via IIS. You place IIS-specific settings into web.config

    I've tested it with netstandard20 DLL and Asp.net Core Web Api and it is all working.

    0 讨论(0)
提交回复
热议问题