NET 8修改appsettings.json并重载

 

确保有文件夹修改权限

发布docker时

dockerfile应该加上RUN chmod -R 757 /app 修改权限

 

实现修改单个对象跟string数组

 

    static async Task UpdateAppSettingsAsync(string keyPath, string newValue)
    {
        Console.WriteLine("StartAPP:chang json:" + keyPath + "=" + newValue);
        var configPath = "appsettings.json";
        var jsonContent = await File.ReadAllTextAsync(configPath);
        var jsonRoot = JsonNode.Parse(jsonContent)!;

        // 分割路径(如 "Logging:LogLevel:Default")
        var keys = keyPath.Split(':');
        var currentNode = jsonRoot;

        // 遍历层级(确保路径存在)
        for (int i = 0; i < keys.Length - 1; i++)
        {
            if (currentNode[keys[i]] == null)
            {
                currentNode[keys[i]] = new JsonObject();
            }
            currentNode = currentNode[keys[i]]!;
        }

        // 设置新值
        currentNode[keys.Last()] = newValue;

        // 保存文件
        var options = new JsonSerializerOptions { WriteIndented = true };
        await File.WriteAllTextAsync(configPath, jsonRoot.ToJsonString(options));
    }


    static async Task UpdateAppSettingsAsync(string keyPath, IEnumerable<string> values)
    {
        Console.WriteLine("StartAPP:chang json:" + keyPath + "=" + JsonSerializer.Serialize(values));
        var configPath = "appsettings.json";
        var jsonContent = await File.ReadAllTextAsync(configPath);
        var jsonRoot = JsonNode.Parse(jsonContent)!;

        var keys = keyPath.Split(':');
        var currentNode = jsonRoot;

        // 遍历层级,确保路径存在
        for (int i = 0; i < keys.Length - 1; i++)
        {
            if (currentNode[keys[i]] == null)
            {
                currentNode[keys[i]] = new JsonObject();
            }
            currentNode = currentNode[keys[i]]!;
        }

        // 创建新的 JSON 数组
        var arrayNode = new JsonArray();
        foreach (var value in values)
        {
            arrayNode.Add(value);
        }

        // 替换或新增数组节点
        currentNode[keys.Last()] = arrayNode;

        // 保存文件
        var options = new JsonSerializerOptions { WriteIndented = true, TypeInfoResolver = new DefaultJsonTypeInfoResolver() };
        await File.WriteAllTextAsync(configPath, jsonRoot.ToJsonString(options));
    }

动态重载

        builder.Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

 

posted @ 2025-04-27 17:19  清风神剑  阅读(118)  评论(0)    收藏  举报