.net core读取appsettings.json配置文件

首先在appsettings.json文件中添加参数,这里以链接数据库为例。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DBConnection": "Data Source=.;Initial Catalog=AdWxSys;User ID=sa;Password=Sa123456;Pooling=true;Max Pool Size=4096;Min Pool Size=0;Connect Timeout=20;"
  },
  "Paths": {
    "Logs": "./Common/logs/",
    "Tokens": "./Common/access_token/"
  },
  "AllowedHosts": "*"
}

在数据库公用类中添加读取代码

string strcon = JsonHelper.GetAppSettings("ConnectionStrings:DBConnection");

设置读取配置文件公共类

public static string GetAppSettings(string key)
{
  var builder = new ConfigurationBuilder()
     .SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
 
  IConfiguration Configuration = builder.Build();
  return Configuration[key];
}

你可能感兴趣的:(C#技术进阶,.netcore,后端)