c# - ASP.NET Core 2.1 应用程序未获得正确的 appsettings.json

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

我有 2 个应用程序

  1. 应用
  2. 类库

App 引用 ClassLibrary 并且都有自己的 appsettings.json 文件。我的类库应用程序没有 startup.cs 或 program.cs,所以我有一个静态类,它应该像这样从本地 appsettings.json 文件中读取:

static class ConfigurationManager
{
    public static IConfiguration AppSetting { get; }
    static ConfigurationManager()
    {
        AppSetting = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();
    }
}

这是类库中的appsettings.json

{
  "AccountsAddress": "http://localhost:55260/api/Accounts/"
}

问题开始于我的应用程序运行时,它调用位于类库中的方法。但是,调用的 appsettings 不是类库中的。它是应用程序本身中的那个。有没有办法指定我要引用类库中的应用程序设置而不是应用程序。

最佳答案

Is there a way to specify that I want to reference the appsettings in the class library instead of the App.

将类库的 appsettings.json 文件重命名为该库独有的名称。

类似于{classlibname}.appsettings.json

重命名后,确保将其设置为复制到输出目录。

重命名后还要确保代码正在调用新名称

//...
.AddJsonFile("classlibname.appsettings.json", optional: true, reloadOnChange: true)
//...

关于c# - ASP.NET Core 2.1 应用程序未获得正确的 appsettings.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52826049/

相关文章:

c# - 在 C# 中显示小数到第 n 位

c# - 如何在 asp.net core 中使用 RestSharp.NetCore

c# - ASP.NET Core 项目中的 MySql 连接字符串错误

c# - 递归实验

C# .Net MVC 非静态字段、方法或属性需要对象引用

c# - C#嵌套Elasticsearch地理点阵列索引未在Kibana中显示

webpack - 使用 webpack 时出现 Bootstrap popper 问题

visual-studio-2015 - DotNetCore 1.0.0 VS2015 Tools Preview2安装失败

c# - 在 ASP.NET Core 中嵌入 View 本地化

c# - 如何将 IFormFile 放入 MVC6 中的 View 模型中