1.准备配置文件appsettings.json
Debug时读取的是appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ApplicationID": "DessInsuranceSystem",
"DAO": {
"Postgre": "User ID=postgres;Password=123456;Host=localhost;Port=5432;Database=MyDB;Pooling=true;",
"PartitionColumn": "TerantId"
}
}
2.具体使用
2.1 新建一个配置文件对象
namespace TestApi.Configuration
{
public class DaoConfig
{
public string ConfigName = "DAO";
public string Postgre { get; set; }
public string PartitionColumn { get; set; }
}
}
2.2 在控制器中使用配置文件中的配置
using Microsoft.Extensions.Configuration;
namespace TestApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly IConfiguration _configuration;
public WeatherForecastController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Get()
{
DaoConfig daoConfig = new DaoConfig();
_configuration.GetSection(daoConfig.ConfigName).Bind(daoConfig);
_configuration.GetSection(daoConfig.ConfigName).Get<DaoConfig>();
}
}
}