public interface IValueProvider
{
bool ContainsPrefix(string prefix); // 判斷資料源是否含指定前綴
ValueProviderResult GetValue(string key); // 依鍵取值,鍵為繫結上下文名稱(含前綴)
}
key 與資料源實際鍵可能不同(資料源鍵含前綴),ContainsPrefix 用於前置檢查。
[Serializable]
public class ValueProviderResult
{
public ValueProviderResult(object rawValue, string attemptedValue, CultureInfo culture);
public object ConvertTo(Type type); // 使用內部 Culture 轉換
public virtual object ConvertTo(Type type, CultureInfo culture); // 指定文化轉換
public string AttemptedValue { get; } // 原始字串表示(供顯示)
public CultureInfo Culture { get; }
public object RawValue { get; } // 原始物件(如 string[])
}
public class NameValueCollectionValueProvider : IUnvalidatedValueProvider, IEnumerableValueProvider, IValueProvider
{
public NameValueCollectionValueProvider(NameValueCollection collection, CultureInfo culture);
public virtual bool ContainsPrefix(string prefix);
public virtual IDictionary<string, string> GetKeysFromPrefix(string prefix);
public virtual ValueProviderResult GetValue(string key);
public virtual ValueProviderResult GetValue(string key, bool skipValidation); // 跳過驗證
}
IEnumerableValueProvider:擴充 GetKeysFromPrefix 回傳前綴符合的鍵值字典,支援集合繫結索引枚舉。IUnvalidatedValueProvider:提供 GetValue(key, skipValidation),允許繫結時略過請求驗證(如允許 HTML 內容)。Add("foo", "1"); Add("foo", "2"))。GetValue("foo").RawValue 回傳 string[]。ConvertTo(int[]) → 逐元素轉換為 int[];ConvertTo(int) → 僅取第一個元素。兩者皆繼承 NameValueCollectionValueProvider,分別包裝 Request.Form 與 Request.QueryString。HttpFileCollectionValueProvider 雖繼承 DictionaryValueProvider,但邏輯類似處理多檔案。
IValueProvider 定義資料存取契約,ValueProviderResult 封裝原始值與文化相關轉換。NameValueCollectionValueProvider 為表單/查詢字串核心實作,支援多值、集合鍵枚舉與無驗證讀取。掌握此基礎可自訂 Provider 整合任意鍵值資料來源。