NETCORE - 读取 appsettings.json 配置数据

NETCORE - 读取 appsettings.json 配置数据

 环境 : net6  webapi 

1. 配置appsettings.json数据

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "authConfig": {
        "Authority": "http://localhost:8092",
        "isHttps": false,
    },
 "TempFiles": "TempFiles/",
    "AllowedHosts": "*"
}

 

 

 

2. 创建配置类 SettingJson.cs

    public class SettingJson
    {
        public string TempFiles { get; set; }
        public ConnectionStrings connectionStrings { get; set; }
        public AuthConfig authConfig { get; set; }
    }

    public class ConnectionStrings
    {
        public string RailCDE { get; set; }
        public string RailAssist { get; set; }
        public string RailPlat { get; set; }
    }

    public class AuthConfig
    {
        public string Authority { get; set; }
        public bool isHttps { get; set; }
    }

 

 

 

3. 注入 Program.cs

//注入配置服务到容器,以便读取appsetting.json
builder.Services.AddOptions().Configure<SettingJson>(option => builder.Configuration.Bind(option));

 

 

4. 接口调用

在构造函数中可获取到值。

   public class MXsdService : IMXsdRepository
    {private readonly IOptionsSnapshot<SettingJson> setting;

        public MXsdService(IOptionsSnapshot<SettingJson> _setting)
        {this.setting = _setting;
        }
    }

 

 

 

 

优化:

创建类 SettingJsonConfig.cs

    public class SettingJsonConfig
    {
        public readonly SettingJson setting;

        public SettingJsonConfig(IOptionsSnapshot<SettingJson> _setting)
        {
            setting = _setting.Value;
        }
    }

 

 

在pragram.cs中注入

builder.Services.AddSingleton<SettingJsonConfig, SettingJsonConfig>();

 

4. 接口调用

在构造函数中可获取到值。

    public class MXsdService : IMXsdRepository
    {
       private readonly SettingJson settingJson;

        public MXsdService(SettingJsonConfig _settingJsonConfig)
        { this.settingJson = _settingJsonConfig.setting;
        }
    }

 

 

 

直接取值方式:

1. 在Program.cs中

var configuration = builder.Configuration;
var authority = configuration.GetSection("AuthConfig:Authority").Value;
string DbConnectionString_RailMate = configuration.GetSection("ConnectionStrings:RailMate").Value;

 

 

2. 在接口中

public class MXsdController : ControllerBase
    {
        private readonly IConfiguration configuration;  public MXsdController(IConfiguration _configuration)
        {
            this.configuration = _configuration;
       var authority = configuration.GetSection("AuthConfig:Authority").Value;
       string DbConnectionString_RailMate = configuration.GetSection("ConnectionStrings:RailMate").Value;
 } }

 

 

 

 

 

 

end

 

posted @ 2023-08-09 15:19  无心々菜  阅读(388)  评论(0编辑  收藏  举报