標籤:play lag stack 通過 http execution method 簡單 binder
模型繫結器
之前或多或少也提到過模型繫結器,方法的形參就是由模型繫結器把參數綁定上去的,今天就說說ModuleBingder那點事
在MVC中有一個介面叫IModuleBinder
// // 摘要: // Defines the method that is required for a model binder. public interface IModelBinder { // // 摘要: // Binds the model to a value by using the specified execution context and binding // context. // // 參數: // modelBindingExecutionContext: // The execution context. // // bindingContext: // The binding context. // // 返回結果: // true if model binding is successful; otherwise, false. bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext); }
當然,這是介面,是沒有實現的,MVC給我們提供了相應的實作類別。DefaultModelBinder,所有的形參都是通過它去處理的。
下面是源碼,這裡可以看到有兩個重要的方法 BindSimpleModel、BindComplexModel 簡單類型綁定與複雜類型的綁定,實際上方法是遞迴調用的,如果參數是對象的話,那就會建立一個對象,然後在綁定每一個屬性,而綁定每一個屬性的方法裡又調用了BindModel方法。
public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { RuntimeHelpers.EnsureSufficientExecutionStack(); if (bindingContext == null) { throw new ArgumentNullException("bindingContext"); } bool flag = false; if (!string.IsNullOrEmpty(bindingContext.ModelName) && !bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName)) { if (!bindingContext.FallbackToEmptyPrefix) { return null; } ModelBindingContext context = new ModelBindingContext { ModelMetadata = bindingContext.ModelMetadata, ModelState = bindingContext.ModelState, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; bindingContext = context; flag = true; } if (!flag) { bool flag2 = ShouldPerformRequestValidation(controllerContext, bindingContext); ValueProviderResult valueProviderResult = bindingContext.UnvalidatedValueProvider.GetValue(bindingContext.ModelName, !flag2); if (valueProviderResult != null) { return this.BindSimpleModel(controllerContext, bindingContext, valueProviderResult); } } if (!bindingContext.ModelMetadata.IsComplexType) { return null; } return this.BindComplexModel(controllerContext, bindingContext); }
protected virtual object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { object objA = propertyBinder.BindModel(controllerContext, bindingContext); if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && object.Equals(objA, string.Empty)) { return null; } return objA; }
MVC是高度可替換的,如果DefaultModelBinder無法很好的實現我們的需求,那麼可以寫自己的ModelBinder。首先定義一個類去繼承自IModelBinder實現BindModel方法,然後在Global裡替換我們的MyModelBinder
public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { //替換 ModelBinders.Binders.DefaultBinder = new MyModelBinder(); } public class MyModelBinder : IModelBinder { public object BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) { //Todo... } } }
MVC5-10 ModleBinder那點事