Created
June 9, 2026 03:06
-
-
Save alonstar/3c347f740a91abcaef621a2fc626081e to your computer and use it in GitHub Desktop.
appsettings.json 的array 改成整串換掉。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.Extensions.Configuration; | |
| using Microsoft.Extensions.Configuration.Json; | |
| public class ArrayReplacingJsonConfigurationSource : JsonConfigurationSource | |
| { | |
| public override IConfigurationProvider Build(IConfigurationBuilder builder) | |
| { | |
| EnsureDefaults(builder); | |
| return new ArrayReplacingJsonConfigurationProvider(this); | |
| } | |
| } | |
| public class ArrayReplacingJsonConfigurationProvider : JsonConfigurationProvider | |
| { | |
| private readonly HashSet<string> _arrayPrefixes = | |
| new(StringComparer.OrdinalIgnoreCase); | |
| public ArrayReplacingJsonConfigurationProvider( | |
| ArrayReplacingJsonConfigurationSource source) : base(source) { } | |
| public override void Load(Stream stream) | |
| { | |
| base.Load(stream); | |
| _arrayPrefixes.Clear(); | |
| foreach (var key in Data.Keys) | |
| { | |
| var segments = key.Split(ConfigurationPath.KeyDelimiter); | |
| for (var i = 0; i < segments.Length; i++) | |
| { | |
| if (!int.TryParse(segments[i], out _)) continue; | |
| // 抽出數字 segment 之前的 prefix,例如: | |
| // "Serilog:WriteTo:0:Name" => "Serilog:WriteTo" | |
| // "Items:0" => "Items" | |
| if (i > 0) | |
| { | |
| _arrayPrefixes.Add( | |
| string.Join(ConfigurationPath.KeyDelimiter, segments.Take(i))); | |
| } | |
| break; | |
| } | |
| } | |
| } | |
| public override IEnumerable<string> GetChildKeys( | |
| IEnumerable<string> earlierKeys, string? parentPath) | |
| { | |
| // 若此路徑的陣列在當前檔案有重新定義,略過所有舊 key 達成整組替換 | |
| if (parentPath is not null && _arrayPrefixes.Contains(parentPath)) | |
| return base.GetChildKeys([], parentPath); | |
| return base.GetChildKeys(earlierKeys, parentPath); | |
| } | |
| } | |
| public static class ArrayReplacingConfigurationExtensions | |
| { | |
| public static IConfigurationBuilder AddArrayReplacingJsonFile( | |
| this IConfigurationBuilder builder, | |
| string path, | |
| bool optional = false, | |
| bool reloadOnChange = false) | |
| { | |
| return builder.Add(new ArrayReplacingJsonConfigurationSource | |
| { | |
| Path = path, | |
| Optional = optional, | |
| ReloadOnChange = reloadOnChange | |
| }); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
.NET 7 之後,目前是對照index 替換,ex ["A", "B"] ["C"] 會變成 ["C", "B"]
但這樣太不直覺,只好自己寫個改成整串換掉。