剑轩

.net core读取配置文件,读取连接字符串。net core读取任意层,任意位置配置

电脑版发表于:2020/2/11 17:05


获取并注入一个对象

在appsettings.json中配置

随便配置一点的:


新建一个类装起来

public class ImgSaveConfig
{
   public string ImgSaveUrl { get; set; }
}

在ConfigureServices中读取配置文件,然后装到对象中去

services.Configure<ImgSaveConfig>(Configuration.GetSection("ImgSave"));//读取配置文件配置的ImgSave相关配置

然后在使用的地方依赖注入即可:

private IOptions<ImgSaveConfig> _options;
private readonly ILogger<UpImgStreamService> _logger;
public UpImgStreamService(ILogger<UpImgStreamService> logger, IOptions<ImgSaveConfig> options)
{
    _logger = logger;
    _options = options;
}



获取单个配置

获取单个对象有两种情况:

public void ConfigureServices(IServiceCollection services)
{
    services.AddGrpc();

    //获取单个
    string test = Configuration["Test"];

    //获取单个(多级中的单个对象)
    string imgSaveUrl = Configuration["ImgSave:ImgSaveUrl"];

    //获取并注入一个对象
    services.Configure<ImgSaveConfig>(Configuration.GetSection("ImgSave"));//读取配置文件配置的ImgSave相关配置
}


如果想要直接获取可以在控制器里边直接注入IConfiguration:


测试代码如下:

private readonly IConfiguration _configuration;
public SendChatGPTController(IConfiguration configuration)
{
    _configuration = configuration;
}

[HttpGet("{id}")]
public string Get(int id)
{
    string visitToken = _configuration["VisitToken"];
    return "value";
}


通过ConfigurationBuilder在任意层获取配置

主要就是SetBasePath设置一个你想要获取配置文章所在的项目

private static IConfigurationRoot BuildConfiguration()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../AJ.JBLand.API/"))
        .AddJsonFile("appsettings.json", optional: true);

    return builder.Build();
}

然后拿到对象获取即可,比如获取连接字符串

//方法1:
string conn = configuration.GetConnectionString("conn_mysql");
//方法2:
string conn_mysql = configuration["ConnectionStrings:conn_mysql"];


关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢