當前位置: 妍妍網 > 碼農

.NET 8 增強了原生數據註解功能

2024-01-30碼農

.NET 8 帶來了新的 DataAnnotations , 您可以使用它驗證字串的最小和最大長度,數值的最小和最大範圍,指定允許和拒絕的值, Base64 字串驗證。

unset unset 如何使用 unset unset

下面的 Product 類使用了 .NET 8 的新數據註解特性。

public classProduct
{
[Length(2, 20)]
publicstring Name { getset; }
[Range(1, 1000, MinimumIsExclusive = true, MaximumIsExclusive = false)]
publicdouble Price { getset; }
[AllowedValues("IOS""Android")]
publicstring Platform { getset; }
[DeniedValues("PC")]
publicstring Source { getset; }
[Base64String]
publicstring Description { getset; }
}


LengthAttribute

System.ComponentModel.DataAnnotations.LengthAttribute 指定字串或集合的下限和上限。比如 Name ,最小值應為 2,最大值應為 20:

[Length(2, 20)]
publicstring Name { getset; }

這意味著 Name 必須包含 2 到 20 個字元,否則無效。

Range

RangeAttribute.MinimumIsExclusive 和 RangeAttribute.MaximumIsExclusive 指定數位是否包含在允許範圍內。

[Range(1, 100, MinimumIsExclusive = true, MaximumIsExclusive = false)]
publicdouble Price { getset; }

Range 表示在指定的範圍內,當前的 Range 的值應該為 1-100, MinimumIsExclusive = true 表示不包含最小值,MaximumIsExclusive = false 表示允許包含最大值,所以 Price 的範圍是 1 < Price <= 100 ,超過這個範圍的值是不允許的。

Base64StringAttribute

Base64StringAttribute 驗證字串是否為有效的 Base64 表示形式,這很簡單。

[Base64String]
publicstring Description { getset; }

AllowedValuesAttribute & DeniedValuesAttribute

AllowedValuesAttribute 和 DeniedValuesAttribute 指定允許和拒絕的值。

[AllowedValues("IOS""Android")]
publicstring Platform { getset; }

上面的 Platform 內容,只允許使用 IOS 和 Android。

[DeniedValues("PC")]
publicstring Source { getset; }

同樣的,上面的 DeniedValues 表示,Source 內容的值不應該為 PC。


.NET 8 給數據註解特性帶來了增強,在日常的開發過程中,也許使用官方提供的數據註解就能滿足我們的需求,而不需要使用第三方的驗證庫,這非常方便。

往期推薦