asp.net core 类库获取appsettings.json的值
项目中添加appsettings.json,属性改成总是复制 { "name": "asp.net", "private": true, "dependencies": { }, "AllowedHosts": "*", "AppSettings": { "BlacklistDB": "Server=your database server;Database=your database name;Integrated Security=SSPI;" } }
NuGet 添加Packages
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Hosting
Microsoft.Extensions.Options
Microsoft.Extensions.Options.ConfigurationExtensions
定义AppSettings.cs类 public class AppSettings { public string BlacklistDB { get; set; } }
定义ConfigurationHelper.cs类 using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using System.IO; public class ConfigurationHelper { public IConfiguration _config { get; set; } public ConfigurationHelper() { _config = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })//ReloadOnChange = true 当appsettings.json被修改时重新加载 .Build(); } public T GetAppSettings<T>(string key) where T : class, new() { var appconfig = new ServiceCollection() .AddOptions() .Configure<T>(_config.GetSection(key)) .BuildServiceProvider() .GetService<IOptions<T>>() .Value; return appconfig; } public T Get<T>(string key) { IConfiguration config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true, true).Build(); return config.GetSection(key).Get<T>(); } //public T GetAppsettings<T>(string key) where T : class, new() //{ // string keyDir = System.IO.Directory.GetCurrentDirectory(); // IConfiguration config = new ConfigurationBuilder() // .SetBasePath(keyDir) // .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })//ReloadOnChange = true 当appsettings.json被修改时重新加载 // .Build(); // var appconfig = new ServiceCollection() // .AddOptions() // .Configure<T>(config.GetSection(key)) // .BuildServiceProvider() // .GetService<IOptions<T>>() // .Value; // return appconfig; //} /// <summary> /// 通过强类型绑定读取配置 /// </summary> /// <typeparam name="Entity">要绑定的类型</typeparam> /// <param name="keyPath">配置文件路径</param> /// <returns>绑定的类</returns> public Entity GetSectionObject<Entity>(string keyPath = null) where Entity : new() { var entity = new Entity(); if (string.IsNullOrEmpty(keyPath)) { //将appsettings.json全部配置绑定到模型 _config.Bind(entity); } else { //将指定路径下的配置项绑定到模型 var section = _config.GetSection(keyPath); section.Bind(entity); } return entity; } }
添加项目类引用 调用 var_connection = new ConfigurationHelper().GetAppSettings<AppSettings>("AppSettings").BlacklistDB; var temp = new ConfigurationHelper().Get<string>("AppSettings:BlacklistDB");