开发手册 欢迎您!
软件开发者资料库

ASP.NET Core使用ConfigurationBuilder读取appsettings.json配置文件

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

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

1)Settings类

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("AppSettings:" + key);            return GetAppStringData;        }        public static string GetConnectionString(string key="DefaultName")        {            var builder = Getbuilder();            var ConnectionString = builder.Build().GetValue("ConnectionStrings:"+key);            return ConnectionString;        }    }

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

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

2、使用新建配置Model的获取配置

需要使用Nuget引用如下,

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

搜索 "Microsoft.Extensions.Options.ConfigurationExtensions" 和 “Microsoft.Extensions.Configuration.Json”,在列表中分别找到它,点击 "安装" 即可。

相关文档VS(Visual Studio)中Nuget的使用

1)appsettings.json配置文件

{  "Logging": {    "LogLevel": {      "Default": "Information",      "Microsoft": "Warning",      "Microsoft.Hosting.Lifetime": "Information"    }  },  "AllowedHosts": "*",  "HangFire": {    "Connection": "Server=127.0.0.1;uid=root;pwd=website;database=Hangfire_DB;AllowLoadLocalInfile=true;Allow User Variables=True;",    "pathMatch": "/hangfire",    "Login": "login",    "PasswordClear": "pwd"  }}

2)AppSettingsModel类

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace WebApplication1{    public class AppSettingsModel    {        public string Connection { get; set; }        public string pathMatch { get; set; }        public string Login { get; set; }        public string PasswordClear { get; set; }    }}

3)ConfSetup配置类

public static class ConfSetup{    private static IConfigurationRoot _configuration;    public static IConfigurationRoot Configuration    {        get        {            if (_configuration == null)            {                var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");                _configuration = builder.Build();                           }            return _configuration;        }        set        {            _configuration = value;        }    }}

4)获取配置项的值

var pathMatch = ConfSetup.Configuration["HangFire:pathMatch"]var connection = ConfSetup.Configuration["HangFire:Connection"]

5)获取配置AppSettingsModel的对象

public static void Main(string[] args){    var hostBuilder = new HostBuilder()   .UseConsoleLifetime()   .ConfigureServices((hostContext, services) =>   {       services.Configure(ConfSetup.Configuration.GetSection("HangFire"));   });      var host = hostBuilder.Build();        var opt = host.Services.GetService>();    AppSettingsModel model = opt.Value;}

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