.NET6读取appsettings.json配置

郑重声明:
  本站发布的内容仅限用于学习和研究目的.请勿用于商业或非法用途,否则后果请用户自负。

.NET6读取appsettings.json配置

基于.NET 6.0创建的WebAPI项目,自动生成的appsettings.json配置模板,在当前项目(dll)中可以通过构造函数注入Configuration来读取。

那么不在当前项目中怎么读取配置呢?例如下面这样的项目,appsesttings.jsonXuanjun.Blog.Server.API中,但是想在Xuanjun.Blog.Server.Core读取配置,怎么实现呢?

image

实现代码如下:

    /// <summary>
    /// 全局配置
    /// </summary>
    public class GlobalConfigContext
    {
        static IConfiguration _configuration;
        static GlobalConfigContext()
        {
            _configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", true, true).Build();
        }
        
        /// <summary>
    	/// 数据库连接信息
    	/// </summary>
		public static XDbConfig DbConfig => 		 _configuration.GetSection("DbConfig").Get<XDbConfig>();
        
      }

这样就可以在任意地方读取配置了。

本文来自博客园,作者:宣君{https://www.nhit.icu/},转载请注明原文链接:https://www.cnblogs.com/ycit/p/17672578.html