美文网首页
ASP.NET Core - 读取配置文件

ASP.NET Core - 读取配置文件

作者: huayueniansi | 来源:发表于2019-01-25 15:33 被阅读0次

    appsettings.json文件


    appsettings.json中配置参数:

    {
      "ConnectionStrings": {
        "Default": "Server=.; Database=demoDb; Trusted_Connection=True;"
      },
      "AllowedHosts": "*"
    }
    

    获取数据库连接字符串


    GetConnectionString

    public Startup(IConfiguration configuration)
    {
        var defaultConnectionString = configuration.GetConnectionString("Default");
    }
    

    获取参数


    GetSection

    返回键值对对象。

    public Startup(IConfiguration configuration)
    {
        var allowedHosts = configuration.GetSection("AllowedHosts").Value;
    }
    

    GetValue

    返回泛型类型。

    public Startup(IConfiguration configuration)
    {
        var allowedHosts = configuration.GetValue<string>("AllowedHosts");
    }
    

    KeyValue

    返回string类型。

    public Startup(IConfiguration configuration)
    {
        var allowedHosts = configuration["AllowedHosts"];
    }
    

    手动初始化IConfiguration


    可以用于单元测试项目,手动初始化IConfiguration

    需要添加程序集:
    Install-Package Microsoft.Extensions.Configuration.Abstractions
    Install-Package Microsoft.Extensions.Configuration.Json

    需要添加引用:
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Configuration.Json;

    var configuration = new ConfigurationBuilder()
        .Add(new JsonConfigurationSource { Path = "appsettings.json" })
        .Build()
        
    // 指定基路径
    var configuration = new ConfigurationBuilder()
        .SetBasePath(System.Environment.CurrentDirectory.Split("bin")[0])
        .Add(new JsonConfigurationSource { Path = "appsettings.json" })
        .Build();
    
    

    相关文章

      网友评论

          本文标题:ASP.NET Core - 读取配置文件

          本文链接:https://www.haomeiwen.com/subject/cdzmjqtx.html