【问题标题】:In a stand-alone .NET Core DLL, how do I get a value from the appsettings.json config file?在独立的 .NET Core DLL 中,如何从 appsettings.json 配置文件中获取值?
【发布时间】:2019-10-30 17:39:24
【问题描述】:

编辑:如果它在控制台应用程序中运行,则从 ASP.NET 控制器传递配置将不起作用。

背景:
- DLL 将随不同的应用程序、一些控制台、一些 ASP.NET MVC 和一些 WebAPI 一起提供
- 我正在构建一个 .NET Core C# 处理 DLL,它需要 appsettings.json 中的多个配置条目。
- 为简单起见,如果可能,我想将 DLL C# 方法全部设为静态。
- 一个示例配置条目将是“SxProcFull”,其值为 true 或 false。 DLL 需要大约 10 个配置项
- DLL 是更大代码库的一部分,从 Web 控制器方法或控制台应用程序的主要方法向下调用多个级别

如何从 DLL 中获取配置条目?

Web 上的大多数示例都是针对 ASP.NET 的,并且通过将配置入口代码放在控制器方法中并将配置服务传递到控制器方法中来过度简化。

.NET Core 文档详细介绍了存在哪些类型的提供程序,但缺少实际示例。

相关链接:

Understanding .net Core Dependency Injection in a console app
https://espressocoder.com/2018/12/03/build-a-console-app-in-net-core-like-a-pro/
https://blog.bitscry.com/2017/05/30/appsettings-json-in-net-core-console-app/
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/?view=aspnetcore-3.0&tabs=windows
还有更多...

编辑:将多应用类型项目移动到背景列表的顶部。

回答:

using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Configuration;

namespace AspNetCoreTestProject2
{
public static class MyConfiguration
{
    private static IConfigurationRoot GetConfigRoot()
    {
        var assemblyLoc = Assembly.GetExecutingAssembly().Location;
        var directoryPath = Path.GetDirectoryName(assemblyLoc);

        var configFilePath = Path.Combine(directoryPath, "appsettings.json");

        if (File.Exists(configFilePath) == false)
        {
            throw new InvalidOperationException("Config file not found");
        }

        IConfigurationBuilder builder = new ConfigurationBuilder();
        builder.AddJsonFile(configFilePath);

        var configRoot = builder.Build();

        return configRoot;
    }

    public static string ConfigGetConnectionStringByName(string connnectionStringName)
    {
        if (string.IsNullOrWhiteSpace(connnectionStringName))
        {
            throw new ArgumentException(nameof(connnectionStringName));
        }

        var root = GetConfigRoot();
        var ret = root.GetConnectionString(connnectionStringName);

        if (string.IsNullOrWhiteSpace(ret))
        {
            throw new InvalidOperationException("Config value cannot be empty");
        }

        return ret;
    }

    public static string ConfigEntryGet(string configEntryName)
    {
        if (string.IsNullOrWhiteSpace(configEntryName))
        {
            throw new ArgumentException(nameof(configEntryName));
        }

        var root = GetConfigRoot();
        var ret = root[configEntryName];

        if (string.IsNullOrWhiteSpace(ret))
        {
            throw new InvalidOperationException("Config value cannot be empty");
        }

        return ret;
    }
}
}

【问题讨论】:

  • 配置项都是简单的键值对,没有复杂的结构。
  • 看看这个answer
  • 感谢 Matt G。我已根据您链接到的 StackOverflow 问题添加了一个可行的解决方案。
  • 生产代码会做更多的验证和异常处理。我还将添加一个 MyConfig C# 包装器类,其中包含用于验证条目的各个条目的方法,以便具有“true”或“false”值的配置条目将接受“true”、“false”、“True”, “假”、“真”、...
  • 这样可以避免用户为桌面应用程序编辑配置文件失败。

标签: c# .net-core console-application


【解决方案1】:
    private readonly IConfiguration _config;

    public YourController(IConfiguration config)
    {
        _config = config;
    }

    public IActionResult Testing()
    {
      string getKey = _config["Token:Key"]
    }

   If you have this sample json
   "Token": {
   "Key": "ktF2YqrBlhfdg444"
   }

【讨论】:

  • Oibuoye,与 BierDav 相同,并不总是从 ASP.NET 应用程序调用。
【解决方案2】:

我不知道你为什么要复制带有 Dlls 的文件夹中的 JSON 并使用这个 JSON。在 Visual Studio 上,您可以选择 JSON 并设置属性“复制到输出路径”。如果你这样做,你可以使用IConfiguration

您从 Controller 类中的 Initialization-Method 获得的类。 例如:

public ApiController(IConfiguration configuration)
{
   Configuration = configuration;
}
private IConfiguration Configuration;

在其他 C# 应用程序上你可以使用这个Nuget 因此,请使用 StreamReader 读取 JSON 文件。

StreamReader sw = new StreamReader("myjason.json");
string json = sw.ReadToEnd();

然后使用JObject

JObject obj = JObject.Parse(json); 
string mainpath = (string)obj["paths"]["mainpath"];

希望对你有帮助。

啤酒节

【讨论】:

  • BierDav,它不仅仅是一个 ASP.NET Core 应用程序。 DLL 是从 ASP.NET 以外的应用程序类型调用的。 DLL 将被复制到调用应用程序的 exe 目录中,该目录也将包含 appsettings json 文件。
  • 我写了On other C# Appliaction you can use this Nuget So read the JSON File with the StreamReader.。怎么了。在其他应用程序类型中,您使用 StreamReader 读取文件(查看代码部分 2)并将其解析为 JObject(查看代码部分 3)。你也可以在曾经的网络中使用它。核心应用。请注意安装 Nuget 并导入此 using Newtonsoft.Json;
猜你喜欢
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
相关资源
最近更新 更多