本文主要介绍通过不新建配置实体类Model方式,使用ConfigurationBuilder来读取appsettings.json配置文件,以及使用示例代码。

1、使用ConfigurationBuilder读取配置项的值

public class Settings
    {
        private static IHttpContextAccessor _HttpContextAccessor;
        public Settings(IHttpContextAccessor httpContextAccessor)
        {
            _HttpContextAccessor = httpContextAccessor;
        }
        public static void Configure(IHttpContextAccessor httpContextAccessor)
        {
            _HttpContextAccessor = httpContextAccessor;
        }
        public static IConfigurationBuilder Getbuilder()
        {
            var builder = new ConfigurationBuilder()
              .SetBasePath(Directory.GetCurrentDirectory())
              .AddJsonFile("appsettings.json");
            return builder;
        }
        public static string GetAppSetting(string key)
        {
            //return Convert.ToString(ConfigurationManager.AppSettings[key]);
            var builder = Getbuilder();
            var GetAppStringData = builder.Build().GetValue<string>("AppSettings:" + key);
            return GetAppStringData;
        }
        public static string GetConnectionString(string key="DefaultName")
        {
            var builder = Getbuilder();
            var ConnectionString = builder.Build().GetValue<string>("ConnectionStrings:"+key);
            return ConnectionString;
        }
    }

2、在Startup中Configure()方法配置

public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
Settings.Configure(httpContextAccessor);
}
}

3、简介下另一种方法使用新建配置Model的方式

需要Nuget引用

 "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0"

使用此方式需要在新建对应appsettings.json中Json字符串的一个实例类,通过以下代码来读取:

 public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddOptions();
services.Configure<AppSettingsModel>(Configuration.GetSection("AppSettings"));
}

相关文档.net core appsettings.json 获取数据库连接字符串

推荐文档

相关文档

大家感兴趣的内容

随机列表