繁体   English   中英

在独立的 .NET Core DLL 中,如何从 appsettings.json 配置文件中获取值?

[英]In a stand-alone .NET Core DLL, how do I get a value from the appsettings.json config file?

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

背景:
- DLL 将附带不同的应用程序,一些控制台,一些 ASP.NET MVC 和一些 WebAPI
- 我正在构建一个 .NET Core C# 处理 DLL 需要来自 appsettings.Z466DEEC766324FCA6D4FZ3857 的几个配置条目
- 如果可能的话,为了简单起见,我想将 DLL C# 方法全部设为 static。
- 一个示例配置条目将是“SxProcFull”,其值为 true 或 false。 DLL 需要大约 10 个配置条目
- DLL 是更大代码库的一部分,从 web controller 方法或控制台应用程序的主要方法向下调用多个级别

如何从 DLL 内部获取配置条目?

Most of the examples on the web are for ASP.NET and oversimplify by putting the config entry code in the controller method with the configuration service passed into the controller method.

.NET 核心文档对存在哪些类型的提供者很长,但对现实世界的例子却很短。

相关链接:

了解控制台应用程序中的 .net 核心依赖注入
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;
    }
}
}

我不知道您为什么将 JSON 复制到带有 Dll 的文件夹中并使用此 JSON。 在 Visual Studio 上,您可以 select 和 JSON 并设置属性“复制到 output 路径”。 如果你这样做,你可以使用IConfiguration

您从 Controller Class 中的初始化方法中获得的 class。 例如。:

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"];

希望能帮助到你。

比尔达夫

    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"
   }

我根据 Matt G 的评论和评论中的链接添加了一个答案。 请看问题的结尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM