In [previous] we talked about object Asynccontrolleractioninvoker, which is called in the controller's Executecore method Asynccontrolleractioninvoker the Invokeaction method of the object to execute the action method.
Public virtual bool Invokeaction (ControllerContext ControllerContext, string actionname) {if (ControllerContext = = Nu ll) throw new ArgumentNullException ("ControllerContext"); if (string. IsNullOrEmpty (ActionName)) throw new ArgumentException (Mvcresources.common_nullorempty, "actionname"); Controllerdescriptor Controllerdescriptor = this. Getcontrollerdescriptor (ControllerContext); Actiondescriptor action = this. Findaction (ControllerContext, Controllerdescriptor, ActionName); if (action = = null) return false; FilterInfo filters = this. Getfilters (ControllerContext, action); try {authorizationcontext AuthorizationContext = this. Invokeauthorizationfilters (ControllerContext, filters. Authorizationfilters, action); if (Authorizationcontext.result! = null) {this. Invokeactionresult (ControllerContext, Authorizationcontext.result); } else {if (ControllerContext.Controller.ValiDaterequest) controlleractioninvoker.validaterequest (ControllerContext); idictionary<string, object> parametervalues = this. Getparametervalues (ControllerContext, action); ActionExecutedContext ActionExecutedContext = this. Invokeactionmethodwithfilters (ControllerContext, filters. Actionfilters, action, parametervalues); This. Invokeactionresultwithfilters (ControllerContext, filters. Resultfilters, Actionexecutedcontext.result); }} catch (ThreadAbortException ex) {throw; } catch (Exception ex) {Exceptioncontext Exceptioncontext = this. Invokeexceptionfilters (ControllerContext, filters. Exceptionfilters, ex); if (!exceptioncontext.exceptionhandled) throw; else this. Invokeactionresult (ControllerContext, Exceptioncontext.result); } return true;
This method is implemented in the Asynccontrolleractioninvoker base class Controlleractioninvoker, and has done a lot of work, we have to gradually decompose this method, first, to obtain the controller's descriptive object method
Protected virtual Controllerdescriptor getcontrollerdescriptor (ControllerContext controllercontext) { Type Controllertype = ControllerContext.Controller.GetType (); return this. Descriptorcache.getdescriptor (Controllertype, (func<controllerdescriptor>) (() = (ControllerDescriptor) New Reflectedcontrollerdescriptor (Controllertype));}
In this method, the Get Controller Descriptor object defaults to reflectedcontrollerdescriptor. Then get the action description object Actiondescriptor According to the action method name,
Protected virtual Actiondescriptor findaction (ControllerContext controllercontext, Controllerdescriptor Controllerdescriptor, String actionname) { return controllerdescriptor.findaction (ControllerContext, ActionName );}
You can see that the controller description object is actually called to get the action Description object method, we based on the obtained default controller description object reflectedcontrollerdescriptor, view its findaction:
public override Actiondescriptor Findaction (ControllerContext controllercontext, String actionname) { if ( ControllerContext = = null) throw new ArgumentNullException ("ControllerContext"); if (string. IsNullOrEmpty (ActionName)) throw new ArgumentException (Mvcresources.common_nullorempty, "ActionName"); MethodInfo Actionmethod = This._selector. Findactionmethod (ControllerContext, actionname); if (Actionmethod = = (MethodInfo) null) return (actiondescriptor) null; else return (actiondescriptor) New Reflectedactiondescriptor (Actionmethod, ActionName, (Controllerdescriptor) this);}
Returns the default is the Reflectedactiondescriptor object that encapsulates the method object MethodInfo to be called.
The next step is to get all the filters applied to the action and the controller based on the controller context and the action description object, get the authorization filter from all the filters obtained, and then call the Onauthorization method on each authorization filter. Determines the result of the returned AuthorizationContext if it is not NULL, the action results method Invokeactionresult is called directly. If it is empty, then the authorization is passed, then the parameters of the action method are obtained, and the parameter values are bound according to the model binder (this will involve another component Imodelbinder, we will talk about it in detail later, here we just need to know that he will bind the parameter value from the requested data according to the parameter name)
Protected virtual idictionary<string, object> getparametervalues (ControllerContext controllercontext, Actiondescriptor actiondescriptor) { dictionary<string, object> Dictionary = new dictionary<string, Object> ((iequalitycomparer<string>) stringcomparer.ordinalignorecase); foreach (Parameterdescriptor parameterdescriptor in Actiondescriptor.getparameters ()) dictionary[ Parameterdescriptor.parametername] = this. Getparametervalue (ControllerContext, parameterdescriptor); Return (idictionary<string, object>) dictionary;}
Protected Virtual Object Getparametervalue (ControllerContext controllercontext, Parameterdescriptor Parameterdescriptor) {Type parametertype = Parameterdescriptor.parametertype; Imodelbinder Modelbinder = this. Getmodelbinder (Parameterdescriptor); Ivalueprovider valueprovider = ControllerContext.Controller.ValueProvider; String str = ParameterDescriptor.BindingInfo.Prefix?? Parameterdescriptor.parametername; Predicate<string> propertyfilter = Controlleractioninvoker.getpropertyfilter (parameterDescriptor); Modelbindingcontext BindingContext = new Modelbindingcontext () {fallbacktoemptyprefix = Parameterdescriptor.b Indinginfo.prefix = = NULL, Modelmetadata = ModelMetadataProviders.Current.GetMetadataForType ((func<object>) n Ull, parametertype), modelname = str, modelstate = ControllerContext.Controller.ViewData.ModelState, PropertyFilter = propertyfilter, Valueprovider = Valueprovider}; RetuRN Modelbinder.bindmodel (ControllerContext, BindingContext)?? Parameterdescriptor.defaultvalue;}
And then the invokeactionmethod method is executed according to the controller description object, the action description object and or the obtained parameters:
Protected virtual ActionResult Invokeactionmethod (ControllerContext controllercontext, Actiondescriptor Actiondescriptor, idictionary<string, object> parameters) { Object actionreturnvalue = Actiondescriptor.execute (controllercontext, parameters); return this. Createactionresult (ControllerContext, Actiondescriptor, Actionreturnvalue); }
Here we find that the key to the method execution is at Actiondescriptor.execute (controllercontext, parameters), and we know that this actiondescriptor is a Reflectedactiondescriptor Object,
public override Object Execute (ControllerContext controllercontext, idictionary<string, object> parameters) { if (ControllerContext = = null) throw new ArgumentNullException ("ControllerContext"); if (parameters = = null) throw new ArgumentNullException ("parameters"); object[] parameters1 = enumerable.toarray<object> (Enumerable.select<parameterinfo, object> ( ienumerable<parameterinfo>) this. Methodinfo.getparameters (), (Func<parameterinfo, object>) (ParameterInfo = Actiondescriptor.extractparameterfromdictionary (parameterinfo, parameters, this. MethodInfo))); return this. Dispatchercache.getdispatcher (this. MethodInfo). Execute (Controllercontext.controller, parameters1);}
In the final step, we find that the Actionmethoddispatcher object is called (this is an internal object that encapsulates the Execute method of the method object MethodInfo that we want to invoke)
public Object Execute (Controllerbase controller, object[] parameters) { return This._executor (Controller, parameters);}
, we find that it calls the Controller object we are currently calling and the parameters of the method to be called as arguments, and _executor is a delegate object, and we can see its value through the Actionmethoddispatcher constructor.
Public Actionmethoddispatcher (MethodInfo MethodInfo) { this._executor = Actionmethoddispatcher.getexecutor ( MethodInfo); This. MethodInfo = MethodInfo;}
From method Getexecutor, continue
private static Actionmethoddispatcher.actionexecutor Getexecutor (MethodInfo MethodInfo) {parameterexpression Paramet ErExpression1 = Expression.parameter (typeof (Controllerbase), "Controller"); ParameterExpression ParameterExpression2 = Expression.parameter (typeof (Object[]), "parameters"); list<expression> list = new list<expression> (); parameterinfo[] Parameters = Methodinfo.getparameters (); for (int index = 0; index < parameters. Length; ++index) {ParameterInfo parameterinfo = Parameters[index]; Unaryexpression unaryexpression = expression.convert (expression) expression.arrayindex (expression) ParameterExpression2, (Expression) Expression.constant ((object) index), parameterinfo.parametertype); List. ADD (Expression) unaryexpression); } methodcallexpression methodcallexpression = Expression.call ((Expression) (!methodinfo.isstatic? Expression.convert (Expression) ParameterExpression1, Methodinfo.reflectedtype): (unaryexpression) null), MethodInfo, (ienumerable<expression>) list); if (Methodcallexpression.type = = typeof (void)) return actionmethoddispatcher.wrapvoidaction (expression.lambda<a Ctionmethoddispatcher.voidactionexecutor> (Expression) methodcallexpression, new parameterexpression[2] { ParameterExpression1, ParameterExpression2}). Compile ()); else return expression.lambda<actionmethoddispatcher.actionexecutor> ((Expression) Expression.convert ( Expression) Methodcallexpression, typeof (Object)), new parameterexpression[2] {parameterExpression1, ParameterExpression2}). Compile ();}
This method is to pass us in the MethodInfo object to invoke, constructs an expression form such as : (controllerbase,object[]) =>controllerbase.methodinfo (object[]) , we find that he is an expression that constructs a delegate of type _executor, and that it is of type
Private Delegate Object Actionexecutor (Controllerbase controller, object[] parameters);
Its invocation is the Actionmethoddispatcher.execute () method, which invokes the method defined in the current controller object to get the return value
Protected virtual ActionResult Createactionresult (ControllerContext controllercontext, Actiondescriptor Actiondescriptor, Object actionreturnvalue) { if (Actionreturnvalue = = null) return (ActionResult) New Emptyresult (); ActionResult ActionResult = Actionreturnvalue as ActionResult; if (ActionResult = = null) ActionResult = (actionresult) new Contentresult () { Content = convert.tostring ( Actionreturnvalue, (IFormatProvider) cultureinfo.invariantculture) }; return actionresult;}
Gets the execution result object ActionResult, encapsulates the object to return in the ActionExecutedContext object, and then calls the Invokeactionresultwithfilters method, The method that will eventually be called is the Invokeactionresult method, and in this method
protected virtual void Invokeactionresult (ControllerContext controllercontext, ActionResult actionresult) { Actionresult.executeresult (ControllerContext);}
Will involve another object ActionResult, which will present the final result to the client!
MVC Request processing process (ii)