前文說道了Action的激活,這裡有個關鍵的操作就是Action參數的映射與模型綁定,這裡即涉及到簡單的string、int等類型,也包含Json等複雜類型,本文詳細分享一下這一過程。(ASP.NET Core 系列目錄) 一、概述 當客戶端發出一個請求的時候,參數可能存在於URL中也可能是在請求的 ...
前文說道了Action的激活,這裡有個關鍵的操作就是Action參數的映射與模型綁定,這裡即涉及到簡單的string、int等類型,也包含Json等複雜類型,本文詳細分享一下這一過程。(ASP.NET Core 系列目錄)
一、概述
當客戶端發出一個請求的時候,參數可能存在於URL中也可能是在請求的Body中,而參數類型也大不相同,可能是簡單類型的參數,如字元串、整數或浮點數,也可能是複雜類型的參數,比如常見的Json、XML等,這些事怎麼與目標Action的參數關聯在一起並賦值的呢?
故事依然是發生在通過路由確定了被請求的Action之後,invoker的創建與執行階段(詳見Action的執行)。
invoker的創建階段,創建處理方法,並根據目標Action的actionDescriptor獲取到它的所有參數,分析各個參數的類型確定對應參數的綁定方法,
invoker的執行階段,調用處理方法,遍歷參數逐一進行賦值。
為了方便描述,創建一個測試Action如下,它有兩個參數,下文以此為例進行描述。:
public JsonResult Test([FromBody]User user,string note = "FlyLolo") { return new JsonResult(user.Code + "|" + user.Name ); }
二、準備階段
1. 創建綁定方法
當收到請求後,由路由系統確定了被訪問的目標Action是我們定義的Test方法, 這時進入invoker的創建階段,前文說過它有一個關鍵屬性cacheEntry是由多個對象組裝而成(發生在ControllerActionInvokerCache的GetCachedResult方法中),其中一個是propertyBinderFactory:
var propertyBinderFactory = ControllerBinderDelegateProvider.CreateBinderDelegate(_parameterBinder,_modelBinderFactory,_modelMetadataProvider,actionDescriptor,_mvcOptions);
看一下CreateBinderDelegate這個方法:
public static ControllerBinderDelegate CreateBinderDelegate(ParameterBinder parameterBinder,IModelBinderFactory modelBinderFactory,
IModelMetadataProvider modelMetadataProvider, ControllerActionDescriptor actionDescriptor, MvcOptions mvcOptions) { //各種驗證 略 var parameterBindingInfo = GetParameterBindingInfo(modelBinderFactory, modelMetadataProvider, actionDescriptor, mvcOptions); var propertyBindingInfo = GetPropertyBindingInfo(modelBinderFactory, modelMetadataProvider, actionDescriptor); if (parameterBindingInfo == null && propertyBindingInfo == null) { return null; } return Bind; async Task Bind(ControllerContext controllerContext, object controller, Dictionary<string, object> arguments) { //後文詳細描述 } }
前文說過,invoker的創建階段就是創建一些關鍵對象和一些用於執行的方法,而propertyBinderFactory 就是眾多方法之中的一個,前文介紹它是一個用於參數綁定的Task,而沒有詳細說明,現在可以知道它被定義為一個名為Bind的Task,最終作為invoker的一部分等待被執行進行參數綁定。
2. 為每個參數匹配Binder
上面的CreateBinderDelegate方法創建了兩個對象parameterBindingInfo 和propertyBindingInfo ,顧名思義,一個用於參數一個用於屬性。看一下parameterBindingInfo 的創建:
private static BinderItem[] GetParameterBindingInfo(IModelBinderFactory modelBinderFactory,IModelMetadataProvider modelMetadataProvider,ControllerActionDescriptor actionDescriptor, MvcOptions mvcOptions) { var parameters = actionDescriptor.Parameters; if (parameters.Count == 0) { return null; } var parameterBindingInfo = new BinderItem[parameters.Count]; for (var i = 0; i < parameters.Count; i++) { var parameter = parameters[i]; //略。。。 var binder = modelBinderFactory.CreateBinder(new ModelBinderFactoryContext { BindingInfo = parameter.BindingInfo, Metadata = metadata, CacheToken = parameter, }); parameterBindingInfo[i] = new BinderItem(binder, metadata); } return parameterBindingInfo; }
可以看到parameterBindingInfo 本質是一個BinderItem[]
private readonly struct BinderItem { public BinderItem(IModelBinder modelBinder, ModelMetadata modelMetadata) { ModelBinder = modelBinder; ModelMetadata = modelMetadata; } public IModelBinder ModelBinder { get; } public ModelMetadata ModelMetadata { get; } }
通過遍歷目標Action的所有參數actionDescriptor.Parameters,根據參數逐一匹配一個對應定的處理對象BinderItem。
如本例,會匹配到兩個Binder:
參數 user ===> {Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder}
參數 note ===> {Microsoft.AspNetCore.Mvc.ModelBinding.Binders.SimpleTypeModelBinder}
這是如何匹配的呢,系統定義了一系列provider,如下圖
圖一
會遍歷他們分別與當前參數做匹配:
for (var i = 0; i < _providers.Length; i++) { var provider = _providers[i]; result = provider.GetBinder(providerContext); if (result != null) { break; } }
同樣以這兩個Binder為例看一下,BodyModelBinderProvider:
public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.BindingInfo.BindingSource != null && context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Body)) { if (_formatters.Count == 0) { throw new InvalidOperationException(Resources.FormatInputFormattersAreRequired( typeof(MvcOptions).FullName, nameof(MvcOptions.InputFormatters), typeof(IInputFormatter).FullName)); } return new BodyModelBinder(_formatters, _readerFactory, _loggerFactory, _options); } return null; }
BodyModelBinder的主要判斷依據是BindingSource.Body 也就是user參數我們設置了[FromBody]。
同理SimpleTypeModelBinder的判斷依據是 if (!context.Metadata.IsComplexType) 。
找到對應的provider後,則會由該provider來new 一個 ModelBinder返回,也就有了上文的BodyModelBinder和SimpleTypeModelBinder。
小結:至此前期準備工作已經完成,這裡創建了三個重要的對象:
1. Task Bind() ,用於綁定的方法,並被封裝到了invoker內的CacheEntry中。
2. parameterBindingInfo :本質是一個BinderItem[],其中的BinderItem數量與Action的參數數量相同。
3. propertyBindingInfo:類似parameterBindingInfo, 用於屬性綁定,下麵詳細介紹。
圖二
三、執行階段
從上一節的小結可以猜到,執行階段就是調用Bind方法,利用創建的parameterBindingInfo和propertyBindingInfo將請求發送來的參數處理後賦值給Action對應的參數。
同樣,這個階段發生在invoker(即ControllerActionInvoker)的InvokeAsync()階段,當調用到它的Next方法的時候,首先第一步State為ActionBegin的時候就會調用BindArgumentsAsync()方法,如下
private Task Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) { switch (next) { case State.ActionBegin: { //略。。。 _arguments = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); var task = BindArgumentsAsync(); }
而BindArgumentsAsync()方法會調用上一節創建的_cacheEntry.ControllerBinderDelegate,也就是Task Bind() 方法
private Task BindArgumentsAsync() { // 略。。。
return _cacheEntry.ControllerBinderDelegate(_controllerContext, _instance, _arguments); }
上一節略了,現在詳細看一下這個方法,
async Task Bind(ControllerContext controllerContext, object controller, Dictionary<string, object> arguments) { var valueProvider = await CompositeValueProvider.CreateAsync(controllerContext); var parameters = actionDescriptor.Parameters; for (var i = 0; i < parameters.Count; i++) //遍歷參數集和,逐一處理 { var parameter = parameters[i]; var bindingInfo = parameterBindingInfo[i]; var modelMetadata = bindingInfo.ModelMetadata; if (!modelMetadata.IsBindingAllowed) { continue; } var result = await parameterBinder.BindModelAsync( controllerContext, bindingInfo.ModelBinder, valueProvider, parameter, modelMetadata, value: null); if (result.IsModelSet) { arguments[parameter.Name] = result.Model; } } var properties = actionDescriptor.BoundProperties; for (var i = 0; i < properties.Count; i++) //略 }
主體就是兩個for迴圈,分別用於處理參數和屬性,依然是以參數處理為例說明。
依然是先獲取到Action所有的參數,然後進入for迴圈進行遍歷,通過parameterBindingInfo[i]獲取到參數對應的BinderItem,這些都準備好後調用parameterBinder.BindModelAsync()方法進行參數處理和賦值。註意這裡傳入了 bindingInfo.ModelBinder ,在parameterBinder中會調用傳入的modelBinder的BindModelAsync方法
modelBinder.BindModelAsync(modelBindingContext);
而這個modelBinder是根據參數匹配的,也就是到現在已經將被處理對象交給了上文的BodyModelBinder、SimpleTypeModelBinder等具體的ModelBinder了。
以BodyModelBinder為例:
public async Task BindModelAsync(ModelBindingContext bindingContext) { //略。。。
var formatterContext = new InputFormatterContext(httpContext,modelBindingKey,bindingContext.ModelState, bindingContext.ModelMetadata, _readerFactory, allowEmptyInputInModelBinding); var formatter = (IInputFormatter)null; for (var i = 0; i < _formatters.Count; i++) { if (_formatters[i].CanRead(formatterContext)) { formatter = _formatters[i]; _logger?.InputFormatterSelected(formatter, formatterContext); break; } else { _logger?.InputFormatterRejected(_formatters[i], formatterContext); } }
var result = await formatter.ReadAsync(formatterContext);
//略。。。
}
部分代碼已省略,剩餘部分可以看到,這裡像上文匹配provider一樣,會遍歷一個名為_formatters的集和,通過子項的CanRead方法來確定是否可以處理這樣的formatterContext。若可以,則調用該formatter的ReadAsync()方法進行處理。這個_formatters集和預設有兩個Formatter, Microsoft.AspNetCore.Mvc.Formatters.JsonPatchInputFormatter} 和 Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter , JsonPatchInputFormatter的判斷邏輯是這樣的
if (!typeof(IJsonPatchDocument).GetTypeInfo().IsAssignableFrom(modelTypeInfo) || !modelTypeInfo.IsGenericType) { return false; }
它會判斷請求的類型是否為IJsonPatchDocument,JsonPatch見本文後面的備註,回到本例,我們經常情況遇到的還是用JsonInputFormatter,此處它會被匹配到。它繼承自TextInputFormatter , TextInputFormatter 又繼承自 InputFormatter,JsonInputFormatter未重寫CanRead方法,採用InputFormatter的CanRead方法。
public virtual bool CanRead(InputFormatterContext context) { if (SupportedMediaTypes.Count == 0) { var message = Resources.FormatFormatter_NoMediaTypes(GetType().FullName, nameof(SupportedMediaTypes)); throw new InvalidOperationException(message); } if (!CanReadType(context.ModelType)) { return false; } var contentType = context.HttpContext.Request.ContentType; if (string.IsNullOrEmpty(contentType)) { return false; } return IsSubsetOfAnySupportedContentType(contentType); }
例如要求ContentType不能為空。本例參數為 [FromBody]User user ,並標識了 content-type: application/json ,通過CanRead驗證後,
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context,Encoding encoding) { //略。。。。using (var streamReader = context.ReaderFactory(request.Body, encoding)) { using (var jsonReader = new JsonTextReader(streamReader)) { jsonReader.ArrayPool = _charPool; jsonReader.CloseInput = false; //略。。var type = context.ModelType; var jsonSerializer = CreateJsonSerializer(); jsonSerializer.Error += ErrorHandler; object model; try { model = jsonSerializer.Deserialize(jsonReader, type); } //略。。。 } } }
可以看到此處就是將收到的請求的內容Deserialize,獲取到一個model返回。此處的jsonSerializer是 Newtonsoft.Json.JsonSerializer ,系統預設採用的json處理組件是Newtonsoft。model返回後,被賦值給對應的參數,至此賦值完畢。
小結:本階段的工作是獲取請求參數的值並賦值給Action的對應參數的過程。由於參數不同,會分配到一些不同的處理方法中處理。例如本例涉及到的provider(圖一)、不同的ModelBinder(BodyModelBinder和SimpleTypeModelBinder)、不同的Formatter等等,實際項目中還會遇到其他的類型,這裡不再贅述。
而文中有兩個需要單獨說明的,在後面的小節里說一下。
四、propertyBindingInfo
上文提到了但沒有介紹,它主要用於處理Controller的屬性的賦值,例如:
public class FlyLoloController : Controller { [ModelBinder] public string Key { get; set; }
有一個屬性Key被標記為[ModelBinder],它會在Action被請求的時候,像給參數賦值一樣賦值,處理方式也類似,不再描述。
五、JsonPatch
上文中提到了JsonPatchInputFormatter,簡要說一下JsonPatch,可以理解為操作json的文檔,比如上文的User類是這樣的:
public class User
{
public string Code { get; set; }
public string Name { get; set; }
//other ...
}
現在我只想修改它的Name屬性,預設情況下我仍然會需要提交這樣的json
{"Code":"001","Name":"張三", .........}
這不科學,從省流量的角度來說也覺得太多了,用JsonPatch可以這樣寫
[
{ "op" : "replace", "path" : "/Name", "value" : "張三" }
]