首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC 1.0 深度剖析 (4):ModelBinder 參數綁定機制全解析

     編輯:關於ASP.NET

MVC 處理請求時,`ControllerActionInvoker.InvokeAction()` 會呼叫 `GetParameterValues()` 為 Action 參數賦值,核心委派給 `IModelBinder.BindModel()`。本文深入原始碼解析三大內建 ModelBinder 選擇邏輯與擴充點。

參數值取得流程

protected virtual object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
{
    Type parameterType = parameterDescriptor.ParameterType;
    IModelBinder binder = GetModelBinder(parameterDescriptor);
    // ... 建立 ModelBindingContext ...
    return binder.BindModel(controllerContext, bindingContext);
}

三大內建 ModelBinder 選擇規則

Action 參數型別使用的 ModelBinder說明
FormCollectionFormCollectionModelBinder綁定表單集合
HttpPostedFileBaseHttpPostedFileBaseModelBinder檔案上傳綁定
其他 (int, string, bool, 複雜型別)DefaultModelBinder最常用、支援巢狀物件、集合、型別轉換

GetModelBinder 解析邏輯

private IModelBinder GetModelBinder(ParameterDescriptor parameterDescriptor)
{
    return parameterDescriptor.BindingInfo.Binder ?? Binders.GetBinder(parameterDescriptor.ParameterType);
}
  • 優先檢查參數上的 `[ModelBinder]` 屬性指定的 Binder。
  • 否則查詢 `ModelBinders.Binders` 靜態字典(`ModelBinderDictionary`)。
  • 字典預設註冊:`typeof(HttpPostedFileBase) -> HttpPostedFileBaseModelBinder`。
  • 未註冊型別回傳 `DefaultModelBinder`。

自訂 ModelBinder 實戰

public class JsonNetModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var json = controllerContext.HttpContext.Request.InputStream.ReadAsString();
        return JsonConvert.DeserializeObject(json, bindingContext.ModelType);
    }
}

// 全域註冊 (Global.asax)
ModelBinders.Binders.Add(typeof(MyComplexModel), new JsonNetModelBinder());
// 或參數標記
public ActionResult Save([ModelBinder(typeof(JsonNetModelBinder))] MyComplexModel model) { ... }

DefaultModelBinder 核心能力

  • 簡單型別轉換 (`TypeDescriptor.GetConverter`)。
  • 複雜物件遞迴綁定屬性 (Prefix 區隔)。
  • 集合/陣列/字典綁定 (索引語法 `list[0].Name`)。
  • 驗證整合 (`ModelState` 自動收集錯誤)。

擴充點總結

  1. 實作 `IModelBinder` 完全自訂綁定邏輯。
  2. 繼承 `DefaultModelBinder` 覆寫 `BindProperty`、`CreateModel` 等虛擬方法微調行為。
  3. 使用 `[ModelBinder]`、`[Bind]`、`[BindNever]` 屬性控制綁定細節。

掌握 ModelBinder 機制,能優雅處理 JSON 請求體、自訂日期格式、加密參數解密等進階場景,是 MVC 進階開發必修課。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved