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

时间:2019-10-30 17:39:24

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

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

背景:
-该DLL将随不同的应用程序,某些控制台,某些ASP.NET MVC和某些WebAPI一起提供
-我正在构建一个.NET Core C#处理DLL,该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;
    }
}
}

3 个答案:

答案 0 :(得分:0)

我不知道为什么您将带有DLL的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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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