【.Net Core学习笔记】appsettings.json配置文件信息读取

在.Net Framework中,一般通过ConfigurationManager.AppSettings["connectionString"];来读取config file中的配置信息。

.Net Core没有提供类似的方法,而是通过配置服务,在控制器初始化的时候实现注入,这种方式很好,也很常见,但是很难做到随时随处可用,比如在Net Library工程中访问配置信息。本文通过自定义中间件的方式,来实现随时随处可访问配置信息

编辑appsettings.json文件

编辑配置文件,增加2个节点,供测试用,如代码所示,我们的目标是获取ConnectionStrings中的连接数据库字符串和AppSettings中的配置项

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo;Trusted_Connection=True;MultipleActiveResultSets=true",
    "ProductionConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo_Production;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "AppSettings": {
    "Item1": "1",
    "Item2": "2",
    "Item3": "3"
  }
  "AllowedHosts": "*"
}

创建自定义中间件

  • 创建一个独立的Net Library工程,比如命名为“MyProject.Common”

  • 新建Confighelper类
public class ConfigHelper
    {
        internal static IConfiguration Configuration { get; set; }

        public static string GetConfig(string key)
        {
            return Configuration[key];
        }

        public static string GetConnectionConfig(string key)
        {
            return Configuration.GetConnectionString(key);
        }
    }

GetConfig:根据Key-Value的方式获取配置信息

GetConnectionConfig:获取配置文件中的连接数据库字符串

  • 新建Config中间件
public class ConfigMiddleware
    {
        private readonly RequestDelegate _next;


        public ConfigMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            ConfigHelper.Configuration = configuration;
        }

        public async Task Invoke(HttpContext context)
        {
            await _next.Invoke(context);
        }
    }

Config中间件使用

  • 注册Config中间件

打开Startup.cs文件,编辑Config方法,加入app.UseMiddleware<ConfigMiddleware>();

  • 随时随地获取配置信息
var conn = ConfigHelper.GetConnectionConfig("DefaultConnection");
var item = ConfigHelper.GetConfig("AppSettings:Item1");

 

发布了50 篇原创文章 · 获赞 18 · 访问量 12万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章