.net core自定义读取配置文件

      最近刚接触.net core 不久,对于ASP.NET Core的新的配置方式做个学习笔记,和之前版本的ASP.NET有很大的区别了,之前是依赖于System.Configuration和XML配置文件web.config,新的配置系统支持多种格式的配置文件。下面就以json配置一波

新建一个项目ASP.NET Core API 应用程序,身份验证默认不进行验证就OK了

新建完成后项目目录下有个 appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "SqlServer": {
    "Host": "192.168.1.0",//地址
    "Port": 6215,//端口号
    "DataBase": "test",//连接数据库
    "UserName": "sa",//用户名
    "Password": "q*^fsZ#B4"//密码
  },
  "AllowedHosts": "*"
}

新建一个AppsettingModels类,用于获取配置数据

   public class SqlServerConn
    {
        public string Host { get; set; }
        public string Port { get; set; }
        public string DataBase { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }

常规的读取配置文件的数据方法

 public void ConfigureServices(IServiceCollection services)
        {
            SqlServerConn sqlServerConn = new SqlServerConn();
            Configuration.GetSection("SqlServer").Bind(sqlServerConn);
            /* 另外的读取方式             
            var sqlServer = Configuration.GetConnectionString("SqlServer");读取节点下的所有配置
            var host = Configuration["SqlServer:Host"];只读取配置里的端口
             */
              //简单的配置连接的地址
             services.AddDbContext<ZDDBContext>(options =>
            {
                options.UseLazyLoadingProxies().UseSqlServer("Server=" + sqlServerConn.Host + "," + sqlServerConn.Port + "; Database=" + sqlServerConn.DataBase + ";Persist Security Info=True;User ID=" + sqlServerConn.UserName + ";password=" + sqlServerConn.Password + ";", a => a.UseRowNumberForPaging());
            }, ServiceLifetime.Scoped);
        }

或者在控制器里直接注入一下

 public class ValuesController : ControllerBase
    {
        private IConfiguration _configuration;
        public ValuesController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public IActionResult test()
        {
            var query = _configuration.GetSection("AllowedHosts");
            return Ok();
        }
    }

在有的时候我们需要在别的类库里直接使用,不便于在写个构造函数来注入一下以及存在了循环引用等问题时,就可以采用自定义的模式,如下:先建SiteConfig类

 /// <summary>
    /// 配置信息读取模型
    /// </summary>
    public static class SiteConfig
    {
        private static IConfigurationSection _appSection = null;

        /// <summary>
        /// api配置信息
        /// </summary>
        public static string AppSetting(string key)
        {
            string str = string.Empty;
            if (_appSection.GetSection(key) != null)
            {
                str = _appSection.GetSection(key).Value;
            }
            return str;
        }

        public static void SetAppSetting(IConfigurationSection section)
        {
            _appSection = section;
        }

        public static string GetSite(string apiName)
        {
            return AppSetting(apiName);
        }
    }

自定义类读取配置

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            SiteConfig.SetAppSetting(Configuration.GetSection("SqlServer"));
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }

使用的时候直接SiteConfig.GetSite("键");

 /// <summary>
        /// 读取配置
        /// </summary>
        /// <returns></returns>
        public void ReadSite()
        {
            SqlConn sqlServerConn = new SqlConn();
            sqlServerConn.Host = SiteConfig.GetSite("Host");
            sqlServerConn.Port = SiteConfig.GetSite("Port");
            sqlServerConn.DataBase = SiteConfig.GetSite("DataBase");
            sqlServerConn.UserName = SiteConfig.GetSite("UserName");
            sqlServerConn.Password = SiteConfig.GetSite("Password");
        }

如果觉得本文有不对的地方,往大佬轻喷,告知我会立即修正。

猜你喜欢

转载自blog.csdn.net/qq_27462223/article/details/87915695