如何在 .net core 5 中将 appsettings.json 的一部分读取为原始字符串?

How can I read part of appsettings.json as raw string in .net core 5?

我使用 C# 和 .net 核心网络 api。 我有以下 appsettings.json:

如何阅读此 appsettings.json 的红色部分(按原样,无需解析 - 原始文本)?

我知道我可以把它放在单独的文件中,然后像这样阅读:

var googleServiceAccount = File.ReadAllText("GoogleServiceAccount.json");

但我想把它们放在 appsettings.json 中。 有什么想法吗?

最好的办法是将 "ServiceAccount" 字段的类型更改为字符串,然后将看似未解释的内容 JSON 进行字符串化,适当地转义(显示为 \" 以转义嵌入的引号)。

{
    "Google": {
        "ServiceAccount": "{ \"type\": \"x\", \"project_id\": \"x\" ... }"
    }
}

此外,you can't have multiline strings in JSON

    "ServiceAccount": "{
       "you": "cant",
       "do": "this"
    }"

所以你必须插入 \n,它会转义 \ 本身,在字符串中留下换行符 \n 或尝试引用 [=] 中的其他建议之一37=].

{
    "Google": {
        "ServiceAccount": "{\n \"type\": \"x\",\n \"project_id\": \"x\" ... \n}"
    }
}

如果你真的想使用某种魔法以某种方式将 JSON 的一部分指定为字符串(例如,知道 JSON 的特定真实部分应该是字符串)那么你会必须构建您自己的魔术解析器(自定义配置提供程序),这将基本上违反 JSON 规范。

我强烈建议你不要这样做,因为它会让每个人感到困惑!

试试这个

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;


IConfiguration configuration = new ConfigurationBuilder()
        .AddJsonFile(@"C:\....\appsettings.json")
        .Build();

 List<KeyValuePair<string,string>> items = configuration
        .GetSection("Google:ServiceAccount")
        .Get<Dictionary<string, string>>()
        .ToList();

foreach (var item in items) Console.WriteLine($"({item.Key},{item.Value})");

或者您可以使用依赖注入而不是配置生成器

public class MyClass
{
   public MyClass(IConfiguration configuration)
{
List<KeyValuePair<string,string>> items = configuration
        .GetSection("Google:ServiceAccount")
        .Get<Dictionary<string, string>>()
        .ToList();
.....
}
}

您可以使用Regex.Replace(string input, string pattern, string replacement);方法来达到您的要求:

var sb = new StringBuilder(); sb.AppendLine("{"); 
var googleServiceAccountItems = _configuration.GetSection("Google:ServiceAccount").Get<Dictionary<string, string>>(); foreach (var item in googleServiceAccountItems) { sb.AppendLine($"\t\"{item.Key}\": \"{item.Value}\""); }
sb.Append("}");

var GoogleServiceAccountString = sb.ToString();
GoogleServiceAccountString = Regex.Replace(GoogleServiceAccountString, "\n|\r|\t", String.Empty);