【问题标题】:How can I share config file like appsettings.json across multiple ASP.NET CORE projects in one solution in Visual Studio 2015?如何在 Visual Studio 2015 的一个解决方案中跨多个 ASP.NET CORE 项目共享配置文件(如 appsettings.json)?
【发布时间】:2016-11-12 04:56:38
【问题描述】:

我在一个解决方案中有 3 个 ASP.NET CORE 项目,我想在一个配置文件(如 appsettings.json)中跨这些项目共享连接字符串信息。

如何在 Visual Studio 2015 中执行此操作?

【问题讨论】:

    标签: asp.net json asp.net-mvc visual-studio asp.net-core


    【解决方案1】:

    您可以像这样在每个项目上使用绝对路径(我假设 appsettings.json 文件位于解决方案根目录中(如 global.json)):

    var settingPath = Path.GetFullPath(Path.Combine(@"../../appsettings.json")); // get absolute path
    var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile(settingPath);
    

    https://github.com/aspnet/Configuration/issues/440

    【讨论】:

    【解决方案2】:

    另一种选择是使用 user secrets 并让应用共享相同的应用 ID。

    作为奖励,您可以将连接字符串保留在您的应用之外,并减少它们因为被推送到源代码控制中而泄漏的可能性。

    【讨论】:

      【解决方案3】:

      设置共享 appsettings.json 文件的绝对路径。

      var relativePath = @"../../The/Relative/Path";
      var absolutePath = System.IO.Path.GetFullPath(relativePath);
      

      然后像这样使用IFileProvider

      var fileProvider = 
          new Microsoft.Extensions.FileProviders.PhysicalFileProvider(absolutePath);
      
      _configuration = new ConfigurationBuilder()
          .SetBasePath(_env.ContentRootPath)
          .AddJsonFile(fileProvider, $"appsettings.json", optional: true, reloadOnChange: true)
          .Build();
      

      或者像这样使用SetBasePath

      var relativePath = @"../../The/Relative/Path";
      var absolutePath = System.IO.Path.GetFullPath(relativePath);
      
      _configuration = new ConfigurationBuilder()
          .SetBasePath(absolutePath)
          .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
          .Build();
      

      虽然文件提供程序方法允许应用程序使用其内容根作为其他静态内容的基本路径,但两者都可以工作。 Adem 的方法也不错。

      【讨论】:

        【解决方案4】:

        可能有更好的方法来做到这一点,但您可以通过在 project.json 文件中添加预编译设置来实现。类似于:

        "scripts": {
          "precompile": [ "../copycommand.bat" ]
        }
        

        copycommand 指向将 AppSettings.json 文件复制到当前目录的批处理命令。如果您面向多个平台,您可能需要为每个平台自定义命令。

        【讨论】:

          【解决方案5】:

          添加一个共享项目,其中包含设置为“如果较新则复制”的 appsettings.json 文件并从其他项目中引用。

          【讨论】:

          • 此解决方案不适用于 .NET 6 RC 2
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-13
          • 1970-01-01
          • 2017-04-23
          • 1970-01-01
          相关资源
          最近更新 更多