.NET 組態系結器會透過組態提供者擷取組態值,並嘗試將這些值系結至物件屬性。 先前,當組態值為 Null 時,系結器會將其視為值完全不存在,因此略過系結。 換句話說,它不會區分 null 值和遺漏值。 對於期待在其組態中明確定義null值能被尊重並正確綁定的使用者,這種行為會造成重大困惑。
此外,JSON 組態提供者先前已將組態中的值轉換成 null 空字串。 這進一步導致混淆,因為系結至這些值的屬性會收到空字串,而不是預期的 Null。
這項變更可解決這兩個問題。 JSON 組態提供者現在會正確報告 null 值而不改變值,而系結器會將值視為 null 有效的輸入,將它們系結為任何其他值。
更新也包含對支援在陣列中系結 null 值的改善,並啟用空陣列的系結。
推出的版本
.NET 10
先前的行為
先前,當組態值是 null時,系結器會將其視為值完全不存在,因此略過系結。 系統無法區分 null 值和遺漏值。
此外,JSON 組態提供者會將組態中的值轉換成 null 空字串。 這會導致係結至這些值的屬性接收空字串,而不是預期的 null。
請考慮下列組態檔 appsettings.json 內容:
{
"NullConfiguration": {
"StringProperty": null,
"IntProperty": null,
"Array1": [null, null],
"Array2": []
}
}
和對應的系結程式代碼:
public class NullConfiguration
{
public NullConfiguration()
{
// Initialize with non-default value to
// ensure binding overrides these values.
StringProperty = "Initial Value";
IntProperty = 123;
}
public string? StringProperty { get; set; }
public int? IntProperty { get; set; }
public string[]? Array1 { get; set; }
public string[]? Array2 { get; set; }
}
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build().GetSection("NullConfiguration");
// Now bind the configuration.
NullConfiguration? result = configuration.Get<NullConfiguration>();
Console.WriteLine($"StringProperty: '{result!.StringProperty}', intProperty: {(result!.IntProperty.HasValue ? result!.IntProperty : "null")}");
Console.WriteLine($"Array1: {(result!.Array1 is null ?
"null" : string.Join(", ", result!.Array1.Select(a => $"'{(a is null ? "null" : a)}'")))}");
Console.WriteLine($"Array2: {(result!.Array2 is null ?
"null" : string.Join(", ", result!.Array2.Select(a => $"'{(a is null ? "null" : a)}'")))}");
輸出:
StringProperty: '', intProperty: 123
Array1: '', ''
Array2: null
輸出的說明:
-
StringProperty:JSON 中的null值被 JSON 提供者轉換為空字串(""),覆寫了初始值。 -
IntProperty:維持不變 (123),因為提供者將null轉換為空字串後,無法剖析成int?,因此保留原始值。 -
Array1:系結至包含兩個空字串的陣列,因為每個null陣列元素都被視為空字串。 -
Array2:由於系結器忽略了 JSON 中的空陣列,null因此仍然保留[]。
新行為
從 .NET 10 開始,null 值現在會正確地繫結到其對應的屬性,包括陣列元素。 即使是空陣列也會正確辨識並系結為空陣列,而不是被忽略。
執行相同的程式代碼範例會使用 JSON 組態提供者產生下列結果:
StringProperty: 'null', intProperty: null
Array1: 'null', 'null'
Array2:
破壞性變更的類型
變更的原因
先前的行為令人困惑,並經常導致用戶投訴。 藉由解決此問題,組態系結程式現在更直覺且一致,可減少混淆,並將行為與用戶預期保持一致。
建議的動作
如果您偏好先前的行為,您可以據以調整組態:
- 使用 JSON 組態提供者時,將
null的值替換為空字串(""),以恢復原始的行為,其中會將空字串繫結而不是使用null。 - 對於支援
null值的其他提供者,請從設定中移除null條目,以重現先前的行為,其中會忽略遺漏值,而現有屬性值保持不變。