当前位置: 首页 > 工具软件 > Node.cs > 使用案例 >

【原创】ASP.NET Core 6 的 Program.cs 中读取配置文件appsettings.json

夏建弼
2023-12-01

appsettings.json文件内容

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "OracleConnection": "User Id=MyOracle;Password=OracalPassword;Data Source=192.168.1.1:1521/MyOracle;PERSIST SECURITY INFO=False"
  }
}

Program.cs 文件中,在适当的位置添加如下代码

//启用Oracle数据库
builder.Services.AddDbContext<OracleDbContext>(options =>
{
    var a = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                 .Build()
                 .GetConnectionString("OracleConnection");
    options.UseOracle(a);
});

然后在数据库上下文文件中,为构造函数添加参数

        public OracleDbContext(DbContextOptions<OracleDbContext> options)
            : base(options)
        {

        }

这样,在其他源码中就可以正常访问数据库了。这些源码中,需要在构造函数中添加对应的参数。

 #region field
        private readonly OracleDbContext oracleContext;
 #endregion

        public WeChatOAController(OracleDbContext oracleContext)
        {
            this.oracleContext = oracleContext;
        }


        [HttpGet]
        [Route("/Zmrbak/v1/Test/CardInfo")]
        public YunTuReaderInfoModel GetCardInfoByCardMac(string? cardMac)
        {
            if (cardMac == null)
            {
                return new YunTuReaderInfoModel { Code = 1 };
            }

            var record = oracleDbContext.读者库?.Where(s => s.读者条码 == cardMac.ToUpper().Trim()).FirstOrDefault();
            if (record == null)
            {
                return new YunTuReaderInfoModel { Code = 1 };
            }

            return GetReaderInfo(record);
        }
 类似资料: