.Net Core 访问 appsettings.json

1、添加 NuGet 包

  Microsoft.Extensions.Configuration

2、通过注入获取 Configuration

  注意:注入获取的必须提前在 StartUp 里面提前注册

    public class Startup
    {
        public IConfiguration Configuration { get; }

        public StartupAutofacIdp(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            //TestConfig 对应json文件 的节点
            services.Configure(Configuration.GetSection("ConnectionStrings"));
        }
    }

    public class TestConfig
    {
        public string Default { get; set; }
        public string Line { get; set; }
    }

appsetting.json

{
  "ConnectionStrings": {
    "Default": "Data Source=.; Initial Catalog=xiaoer; User Id=sa; Password=123456;",
    "Line": "Data Source=.; Initial Catalog=xiaoer; User Id=sa; Password=1234567890;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

    public class HomeController : Controller
    {
        private TestConfig testConfig;
        public IConfiguration Configuration;
        public HomeController(IOptions options, IConfiguration configuration)
        {
            testConfig = options.Value;
            Configuration = configuration;
        }

        public IActionResult Index()
        {
            /*
             * 2种方式
             * 1、通过 StartUp 提前注册实体类访问
             * 2、使用 Configuration 实例访问
             */
            TestConfig test = new TestConfig();
            Configuration.GetSection("ConnectionStrings").Bind(test);
            ViewBag.Test = test;
            return View(testConfig);
        } 
    }

3、通过加载对应的文件绑定 Configuration 实例

    public class Config
    {
        /// 
        ///  appsettings.json 文件 也可以是任何自定义的 json 文件
        /// 
        private static IConfiguration Configuration;  
        static Config()
        {
            if (Configuration == null)
            {
                var builder = new ConfigurationBuilder();
                builder.SetBasePath(Directory.GetCurrentDirectory());
                builder.AddJsonFile("appsettings.json", false, true);
                Configuration = builder.Build();
            } 
        }
    } 

  

你可能感兴趣的:(.Net Core 访问 appsettings.json)