ASP .NET Core 2.1从没有Startup.cs的appsettings.json中获取变量

时间:2018-10-15 12:10:37

标签: c# asp.net-core asp.net-core-mvc

这是我的appsettings.json。它位于没有startup.cs的类库中。我想知道是否有可能从那里获取变量以在本地使用?

{
  "AccountsAddress": "http://localhost:55260/api/Accounts/",
  "ApplicationUsersAddress": "http://localhost:55260/api/ApplicationUsers/"
}

public static class Manager
{
    public static IConfiguration AppSetting { get; }
    static Manager()
    {
        AppSetting = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
    }
}

enter image description here

这是我图书馆的结构

1 个答案:

答案 0 :(得分:3)

{
  "AccountsAddress": "http://localhost:55260/api/Accounts/",
  "ApplicationUsersAddress": "http://localhost:55260/api/ApplicationUsers/",
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

创建一个myConfig.cs文件并粘贴以下代码。

using Microsoft.Extensions.Configuration;
static class ConfigurationManager
{
    public static IConfiguration AppSetting { get; }
    static ConfigurationManager()
    {
        AppSetting = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("YouAppSettingFile.json")
                .Build();
    }
}

现在您可以像这样使用它:

string value = ConfigurationManager.AppSetting["value_Key"];

enter image description here