private static bool IsSameAction(ActionDescriptor descriptor1, ActionDescriptor descriptor2)
        {
            ParameterDescriptor[] parameters1 = descriptor1.GetParameters();
            ParameterDescriptor[] parameters2 = descriptor2.GetParameters();

            bool same = descriptor1.ControllerDescriptor.ControllerName.Equals(descriptor2.ControllerDescriptor.ControllerName, StringComparison.OrdinalIgnoreCase) &&
                        descriptor1.ActionName.Equals(descriptor2.ActionName, StringComparison.OrdinalIgnoreCase) &&
                        (parameters1.Length == parameters2.Length);

            if (same)
            {
                for (int i = parameters1.Length - 1; i >= 0; i--)
                {
                    if (parameters1[i].ParameterType == parameters2[i].ParameterType)
                    {
                        continue;
                    }

                    same = false;
                    break;
                }
            }

            return(same);
        }
Esempio n. 2
0
        private bool HasAcceptableParameters(
            ActionDescriptor actionDescriptor,
            object model   = null,
            object message = null)
        {
            var parameters = actionDescriptor.GetParameters();

            // Has either no parameters OR
            if (!parameters.Any())
            {
                return(true);
            }

            // Has 1 parameter ...
            if (parameters.Count() == 1 &&
                (    // ...that accepts either the Model or the Message (and we have a model or a message)
                    (model != null && parameters.First().ParameterType.IsAssignableFrom(model.GetType())) ||
                    (message != null && parameters.First().ParameterType.IsAssignableFrom(message.GetType()))))
            {
                return(true);
            }

            // Has 2 parameters ...
            if (parameters.Count() == 2 && model != null && message != null &&
                ((    // ... where one accepts the Model and the other accepts the Message
                     parameters.First().ParameterType.IsAssignableFrom(model.GetType()) &&
                     parameters.Last().ParameterType.IsAssignableFrom(message.GetType())) ||
                 (parameters.Last().ParameterType.IsAssignableFrom(model.GetType()) &&
                  parameters.First().ParameterType.IsAssignableFrom(message.GetType()))))
            {
                return(true);
            }

            return(false);
        }
Esempio n. 3
0
        public IEnumerable <System.Web.Mvc.Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            //if ((controllerContext.Controller is ProductController || controllerContext.Controller is ProductsController) &&
            //    actionDescriptor.ActionName.Equals("ProductList",
            //    StringComparison.InvariantCultureIgnoreCase))
            if ((actionDescriptor.ControllerDescriptor.ControllerName == "Product" || actionDescriptor.ControllerDescriptor.ControllerName == "Products") &&
                actionDescriptor.ActionName.Equals("ProductList", StringComparison.InvariantCultureIgnoreCase))
            {
                if (controllerContext.RouteData.Values["area"] != null &&
                    (controllerContext.RouteData.Values["area"].ToString() == "Admin" || controllerContext.RouteData.Values["area"].ToString() == "Vendor"))
                {
                    //return new List<System.Web.Mvc.Filter>() { new System.Web.Mvc.Filter(this, FilterScope.Action, 0) };
                }
            }

            if ((actionDescriptor.ControllerDescriptor.ControllerName == "Home") &&
                actionDescriptor.ActionName.Equals("Index",
                                                   StringComparison.InvariantCultureIgnoreCase))
            {
                return(new List <System.Web.Mvc.Filter>()
                {
                    new System.Web.Mvc.Filter(this, FilterScope.Action, 0)
                });
            }

            var a = actionDescriptor.GetCustomAttributes(true);
            var b = actionDescriptor.GetFilterAttributes(true);
            var c = actionDescriptor.GetParameters();

            return(new List <System.Web.Mvc.Filter>());
        }
Esempio n. 4
0
        public bool IsSameAction(ActionDescriptor descriptor)
        {
            var desc = descriptor as ReflectedActionDescriptor;

            if (desc != null)
            {
                bool sameAction = ActionDescriptor.MethodInfo == desc.MethodInfo;
                if (sameAction)
                {
                    return(true);
                }
            }
            ParameterDescriptor[] parameters1 = descriptor.GetParameters();

            bool same = descriptor.ControllerDescriptor.ControllerName.Equals(ActionDescriptor.ControllerDescriptor.ControllerName, StringComparison.OrdinalIgnoreCase) &&
                        descriptor.ActionName.Equals(ActionDescriptor.ActionName, StringComparison.OrdinalIgnoreCase) &&
                        (parameters1.Length == _actionParameterDescriptors.Length);

            if (same)
            {
                for (int i = parameters1.Length - 1; i >= 0; i--)
                {
                    if (parameters1[i].ParameterType == _actionParameterDescriptors[i].ParameterType)
                    {
                        continue;
                    }

                    same = false;
                    break;
                }
            }

            return(same);
        }
Esempio n. 5
0
        private IDictionary <string, object> GetMultiObjectsFormString(string input, ActionDescriptor action)
        {
            Dictionary <string, object> dict = jss.DeserializeObject(input) as Dictionary <string, object>;

            //if( dict.Count != action.Parameters.Length )
            //    throw new ArgumentException("客户端提交的数据项与服务端的参数项的数量不匹配。");

            var Parameters = action.GetParameters();
            Dictionary <string, object> parameters = new Dictionary <string, object>(Parameters.Length);

            for (int i = 0; i < Parameters.Length; i++)
            {
                var    parameterDescriptor = Parameters[i];
                string name  = parameterDescriptor.ParameterName;
                object value = (from kv in dict
                                where string.Compare(kv.Key, parameterDescriptor.BindingInfo.Prefix + name, StringComparison.OrdinalIgnoreCase) == 0
                                select kv.Value).FirstOrDefault();

                if (value != null)
                {
                    Type destType = parameterDescriptor.ParameterType.GetRealType();

                    MethodInfo method    = s_methodConvertToType.MakeGenericMethod(destType);
                    object     parameter = method.FastInvoke(jss, new object[] { PropertyFilter(value, parameterDescriptor) });
                    parameters[name] = parameter;
                }
                else
                {
                    parameters[name] = parameterDescriptor.DefaultValue;
                }
            }
            return(parameters);
        }
Esempio n. 6
0
        private void Log(string methodName, ControllerDescriptor controllerDescriptor, ActionDescriptor actionDescriptor, IDictionary <string, object> actionParameters)
        {
            if (Execute)
            {
                var actionParametersToLog = new Dictionary <string, object>();

                foreach (var parameter in actionDescriptor.GetParameters())
                {
                    var attr = parameter.GetCustomAttributes(typeof(NoLogAttribute), false);
                    if (attr.Length == 0)
                    {
                        actionParametersToLog.Add(parameter.ParameterName, actionParameters[parameter.ParameterName]);
                    }
                }

                string parameters = string.Empty;
                if (actionParametersToLog.Count > 0)
                {
                    parameters = _jsonSerializer.Serialize(actionParametersToLog);
                }

                var message = String.Format("{0} controller:{1} action: {2} params:{3}", methodName, controllerDescriptor.ControllerName, actionDescriptor.ActionName, parameters);
                _log.Debug(message);
            }
        }
Esempio n. 7
0
        protected override IDictionary <string, object> GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            ThriftActionResult context = ThriftActionResult.GetThriftResult(controllerContext.HttpContext);

            //check if current request is thrift
            if (context != null && context.GetParameterValues != null)
            {
                Dictionary <string, object> parameterDictionary = new Dictionary <string, object>();
                context.GetParameterValues(context.Input, parameterDictionary);

                context.Parameters = parameterDictionary;

                Dictionary <string, object> MatchDict = new Dictionary <string, object>();
                //ignore case
                foreach (var pd in actionDescriptor.GetParameters())
                {
                    string key = pd.ParameterName.ToLower();
                    if (parameterDictionary.ContainsKey(key))
                    {
                        MatchDict.Add(pd.ParameterName, parameterDictionary[key]);
                    }
                }

                return(MatchDict);
            }

            return(base.GetParameterValues(controllerContext, actionDescriptor));
        }
Esempio n. 8
0
 public IEnumerable <object> GetParameterValues(ActionDescriptor actionDescriptor)
 {
     foreach (ParameterDescriptor parameterDescriptor in actionDescriptor.GetParameters())
     {
         string prefix = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;
         yield return(GetParameterValue(parameterDescriptor, prefix));
     }
 }
Esempio n. 9
0
        /// <summary>
        /// Gets the values of the action-method parameters.
        /// </summary>
        public virtual IDictionary <string, object> GetParameterValues()
        {
            var dictionary = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            foreach (var parameterDescriptor in ActionDescriptor.GetParameters())
            {
                dictionary[parameterDescriptor.ParameterName] = GetParameterValue(parameterDescriptor);
            }
            return(dictionary);
        }
Esempio n. 10
0
            protected override ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary <string, object> parameters)
            {
                var uowParam = actionDescriptor.GetParameters().FirstOrDefault(x => x.ParameterType == typeof(IUnitOfWork));

                if (uowParam != null)
                {
                    var connectionKey = controllerContext.Controller.GetType().GetCustomAttribute <ConnectionKeyAttribute>();
                    if (connectionKey == null)
                    {
                        throw new ArgumentNullException("connectionKey");
                    }

                    using (var connection = SqlConnections.NewByKey(connectionKey.Value))
                        using (var uow = new UnitOfWork(connection))
                        {
                            parameters[uowParam.ParameterName] = uow;
                            var result = base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
                            uow.Commit();
                            return(result);
                        }
                }

                var cnnParam = actionDescriptor.GetParameters().FirstOrDefault(x => x.ParameterType == typeof(IDbConnection));

                if (cnnParam != null)
                {
                    var connectionKey = controllerContext.Controller.GetType().GetCustomAttribute <ConnectionKeyAttribute>();
                    if (connectionKey == null)
                    {
                        throw new ArgumentNullException("connectionKey");
                    }

                    using (var cnn = SqlConnections.NewByKey(connectionKey.Value))
                    {
                        parameters[cnnParam.ParameterName] = cnn;
                        return(base.InvokeActionMethod(controllerContext, actionDescriptor, parameters));
                    }
                }

                return(base.InvokeActionMethod(controllerContext, actionDescriptor, parameters));
            }
Esempio n. 11
0
        public ActionResult Index()
        {
            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(typeof(HomeController));
            ActionDescriptor     actionDescriptor     = controllerDescriptor.FindAction(ControllerContext, "DemoAction");
            Dictionary <ParameterDescriptor, IModelBinder> binders = new Dictionary <ParameterDescriptor, IModelBinder>();

            foreach (ParameterDescriptor parameterDescriptor in actionDescriptor.GetParameters())
            {
                binders.Add(parameterDescriptor, this.GetModelBinder(parameterDescriptor));
            }
            return(View(binders));
        }
Esempio n. 12
0
        protected virtual IDictionary <string, object> GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            Dictionary <string, object> parametersDict = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            ParameterDescriptor[] parameterDescriptors = actionDescriptor.GetParameters();

            foreach (ParameterDescriptor parameterDescriptor in parameterDescriptors)
            {
                parametersDict[parameterDescriptor.ParameterName] = GetParameterValue(controllerContext, parameterDescriptor);
            }
            return(parametersDict);
        }
Esempio n. 13
0
        private string GetActionName(ActionDescriptor mvcActionDescriptor)
        {
            var sb = new StringBuilder(mvcActionDescriptor.ActionName + "(");

            foreach (var parameter in mvcActionDescriptor.GetParameters())
            {
                sb.Append(parameter.ParameterType + " ");
                sb.Append(parameter.ParameterName + ", ");
            }
            sb.Remove(sb.Length - 2, 2);
            sb.Append(")");
            return(sb.ToString());
        }
Esempio n. 14
0
        private IDictionary <string, object> GetMultiObjectsFormRequest(HttpRequest request, ActionDescriptor action)
        {
            string xml = request.ReadInputStream();

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xml);

            XmlNode root = doc.LastChild;

            //if( root.ChildNodes.Count != action.Parameters.Length )
            //    throw new ArgumentException("客户端提交的数据项与服务端的参数项的数量不匹配。");

            var Parameters = action.GetParameters();
            Dictionary <string, object> parameters = new Dictionary <string, object>(Parameters.Length);

            for (int i = 0; i < Parameters.Length; i++)
            {
                var     parameterDescriptor = Parameters[i];
                string  name = parameterDescriptor.ParameterName;
                XmlNode node = (from n in root.ChildNodes.Cast <XmlNode>()
                                where string.Compare(n.Name, parameterDescriptor.BindingInfo.Prefix + name, StringComparison.OrdinalIgnoreCase) == 0
                                select n).FirstOrDefault();

                if (node != null)
                {
                    object parameter = null;
                    Type   destType  = parameterDescriptor.ParameterType.GetRealType();

                    if (destType.IsSupportableType())
                    {
                        parameter = ModelHelper.SafeChangeType(node.InnerText, destType);
                    }
                    else
                    {
                        parameter = XmlDeserialize(node.OuterXml, destType, request.ContentEncoding);
                    }

                    if (parameter == null)
                    {
                        parameter = parameterDescriptor.DefaultValue;
                    }
                    parameters[name] = parameter;
                }
            }

            return(parameters);
        }
Esempio n. 15
0
        public IDictionary <string, object> GetParameters(HttpRequest request, ActionDescriptor action)
        {
            var Parameters = action.GetParameters();

            if (Parameters.Length == 1)
            {
                object value = GetObjectFromRequest(request, Parameters[0].ParameterType.GetRealType());
                return(new Dictionary <string, object> {
                    { Parameters[0].ParameterName, value }
                });
            }
            else
            {
                return(GetMultiObjectsFormRequest(request, action));
            }
        }
Esempio n. 16
0
 protected override IDictionary <string, object> GetParameterValues(ControllerContext controllerContext,
                                                                    ActionDescriptor actionDescriptor)
 {
     if (controllerContext.RouteData.DataTokens.ContainsKey("IsXmlRpc") &&
         (bool)controllerContext.RouteData.DataTokens["IsXmlRpc"])
     {
         IList <XmlRpcParameter> parameters =
             controllerContext.RouteData.Values["parameters"] as IList <XmlRpcParameter>;
         IDictionary <string, object> mappedParameters =
             XmlRpcParameterMapper.Map(actionDescriptor.GetParameters(), parameters);
         foreach (var mappedParameter in mappedParameters)
         {
             controllerContext.RouteData.Values.Add(mappedParameter.Key, mappedParameter.Value);
         }
     }
     return(base.GetParameterValues(controllerContext, actionDescriptor));
 }
Esempio n. 17
0
        //returns a method name like "Index(int id)" instead of "Index"
        internal static string GetMethodNameWithParameters(this ActionDescriptor mvcActionDescriptor)
        {
            var sb = new StringBuilder(mvcActionDescriptor.ActionName + "(");

            var parameters = mvcActionDescriptor.GetParameters();

            foreach (var parameter in parameters)
            {
                sb.Append(parameter.ParameterType + " ");
                sb.Append(parameter.ParameterName + ", ");
            }
            if (parameters.Length > 0)
            {
                sb.Remove(sb.Length - 2, 2);
            }
            sb.Append(")");
            return(sb.ToString());
        }
Esempio n. 18
0
        /// <summary>
        /// 格式化Action的参数字符串
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public static string FormatParams(ActionDescriptor action)
        {
            var param  = action.GetParameters();
            var result = new StringBuilder();

            if (param.Length > 0)
            {
                foreach (var item in param)
                {
                    result.Append(string.Format("Type:{0}, Name:{1}; ", item.ParameterType, item.ParameterName));
                }
                return(result.ToString());
            }
            else
            {
                return(null);
            }
        }
Esempio n. 19
0
    protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
    {
        ViewDataDictionary model = null;

        // get our query parameter
        var query = GetParameterValue(controllerContext, actionDescriptor.GetParameters().Where(x => x.ParameterName == "query").FirstOrDefault());

        // pass the query to our mediator
        if (query is DetailsQuery)
        {
            model = new ViewDataDictionary(this.mediator.Request((DetailsQuery)query));
        }
        // return the view with read model returned from mediator
        return(new ViewResult
        {
            ViewName = actionDescriptor.ActionName,
            ViewData = model
        });
    }
        private static string GetSamplePath(RequestContext requestContext, ActionDescriptor action)
        {
            var urlHelper = new UrlHelper(requestContext);

            var actionNameAttrib = action.GetCustomAttributes(inherit: true).OfType <ActionNameAttribute>().FirstOrDefault();

            // This is tricky because some of the action parameters may not be meant to come from the route.
            // e.g. they could come from a POST body.
            // In that case, they may end up as bogus query string params on the path, which is a bit buggy
            var routeValues = new RouteValueDictionary();

            foreach (ParameterDescriptor param in action.GetParameters())
            {
                routeValues.Add(param.ParameterName, GetDefaultValue(param));
            }

            return(urlHelper.Action(
                       actionNameAttrib != null ? actionNameAttrib.Name : action.ActionName,
                       action.ControllerDescriptor.ControllerName.ToLowerInvariant(),
                       routeValues));
        }
Esempio n. 21
0
        protected IEnumerable <ParameterDescriptor> FindActionParameters <T>(
            ActionDescriptor actionDescriptor,
            bool requireDefaultConstructor             = true,
            bool throwIfNotFound                       = true,
            Func <ParameterDescriptor, bool> predicate = null)
        {
            Guard.NotNull(actionDescriptor, nameof(actionDescriptor));

            var t = typeof(T);

            var query = actionDescriptor
                        .GetParameters()
                        .Where(x => t.IsAssignableFrom(x.ParameterType));

            if (predicate != null)
            {
                query = query.Where(predicate);
            }

            if (throwIfNotFound && !query.Any())
            {
                throw new InvalidOperationException(
                          $"A controller action method with a '{this.GetType().Name}' attribute requires an action parameter of type '{t.Name}' in order to execute properly.");
            }

            if (requireDefaultConstructor)
            {
                foreach (var param in query)
                {
                    if (!param.ParameterType.HasDefaultConstructor())
                    {
                        throw new InvalidOperationException($"The parameter '{param.ParameterName}' must have a default parameterless constructor.");
                    }
                }
            }

            return(query);
        }
Esempio n. 22
0
        public static object InvokeAction(this Controller controller, string actionName)
        {
            IModelBinder                modelBinder          = new MyDefaultModelBinder();
            ControllerDescriptor        controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            ActionDescriptor            actionDescriptor     = controllerDescriptor.FindAction(controller.ControllerContext, actionName);
            Dictionary <string, object> arguments            = new Dictionary <string, object>();

            foreach (ParameterDescriptor parameterDescriptor in actionDescriptor.GetParameters())
            {
                string modelName = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;
                ModelBindingContext bindingContext = new ModelBindingContext
                {
                    FallbackToEmptyPrefix = parameterDescriptor.BindingInfo.Prefix == null,
                    ModelMetadata         = ModelMetadataProviders.Current.GetMetadataForType(null, parameterDescriptor.ParameterType),
                    ModelName             = modelName,
                    ModelState            = controller.ModelState,
                    ValueProvider         = controller.ValueProvider
                };
                object argument = modelBinder.BindModel(controller.ControllerContext, bindingContext);
                arguments.Add(parameterDescriptor.ParameterName, argument);
            }
            return(actionDescriptor.Execute(controller.ControllerContext, arguments));
        }
Esempio n. 23
0
        protected override IDictionary <string, object> GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            var directRequest  = controllerContext.HttpContext.Items[DirectRequest.DirectRequestKey] as DirectRequest;
            var parametersDict = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            ParameterDescriptor[] parameterDescriptors = actionDescriptor.GetParameters();

            if (directRequest == null)
            {
                throw new NullReferenceException(DirectResources.Common_DirectRequestIsNull);
            }

            if (!directRequest.IsFormPost && directRequest.Data != null)
            {
                controllerContext.Controller.ValueProvider = new DirectValueProvider(directRequest, parameterDescriptors);
            }

            foreach (ParameterDescriptor parameterDescriptor in parameterDescriptors)
            {
                parametersDict[parameterDescriptor.ParameterName] = GetParameterValue(controllerContext, parameterDescriptor);
            }
            return(parametersDict);
        }
        public override RequestAnalysisResult GetRequestAnalysis(RequestAnalysisContext analysisContext)
        {
            RouteData             routeData      = analysisContext.RouteData;
            RequestAnalysisResult analysisResult = new RequestAnalysisResult();
            string controllerName = routeData.Values.TryGetValue("controller", out object controller) ? controller.ToString() : null;

            analysisResult.ActionName = routeData.Values.TryGetValue("action", out object action) ? action.ToString() : null;

            if (!string.IsNullOrEmpty(controllerName) && !string.IsNullOrEmpty(analysisResult.ActionName))
            {
                IControllerFactory   controllerFactory    = ControllerBuilder.Current.GetControllerFactory();
                RequestContext       requestContext       = new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData);
                IController          controllerInstance   = controllerFactory.CreateController(requestContext, controllerName);
                ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerInstance.GetType());
                ControllerContext    controllerContext    = new ControllerContext(requestContext, controllerInstance as ControllerBase);
                ActionDescriptor     actionDescriptor     = controllerDescriptor.FindAction(controllerContext, analysisResult.ActionName);

                analysisResult.Url            = HttpContext.Current.Request.Url.ToString();
                analysisResult.Mode           = Mode;
                analysisResult.Values         = routeData.Values;
                analysisResult.DataTokens     = routeData.DataTokens;
                analysisResult.ControllerName = controllerDescriptor.ControllerType.FullName;
                analysisResult.Parameters     = actionDescriptor.GetParameters().Select(parameter => parameter.ParameterName).ToArray();

                analysisResult.SupportedHttpMethods = actionDescriptor.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true)
                                                      .Select(methodAttribute => methodAttribute.GetType().Name.Replace("Attribute", "").Replace("Http", "")).ToArray();

                analysisResult.SupportedHttpMethods = analysisResult.SupportedHttpMethods.Count() == 0
                    ? new string[1] {
                    "All"
                } : analysisResult.SupportedHttpMethods;

                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LookupPrefix);
                analysisResult.FilePath = LookupFilePath(path, analysisResult.ControllerName);
            }
            return(analysisResult);
        }
Esempio n. 25
0
 public override ParameterDescriptor[] GetParameters()
 {
     return(descriptor?.GetParameters() ?? new ParameterDescriptor[0]);
 }
 public override ParameterDescriptor[] GetParameters()
 {
     return(_internalDescriptor.GetParameters());
 }
Esempio n. 27
0
        public IDictionary <string, object> GetParameters(HttpRequest request, ActionDescriptor action)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            ParameterDescriptor[]        ActionParam = action.GetParameters();
            IDictionary <string, object> parameters  = new Dictionary <string, object>(ActionParam.Length);

            for (int i = 0; i < ActionParam.Length; i++)
            {
                ParameterDescriptor p = ActionParam[i];

                if (p.ParameterInfo.IsOut)
                {
                    continue;
                }

                if (p.ParameterType == ReflectionHelper.VoidType)
                {
                    continue;
                }

                if (p.ParameterType == typeof(NameValueCollection))
                {
                    if (string.Compare(p.ParameterName, "Form", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        parameters[p.ParameterName] = request.Form;
                    }
                    else if (string.Compare(p.ParameterName, "QueryString", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        parameters[p.ParameterName] = request.QueryString;
                    }
                    else if (string.Compare(p.ParameterName, "Headers", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        parameters[p.ParameterName] = request.Headers;
                    }
                    else if (string.Compare(p.ParameterName, "ServerVariables", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        parameters[p.ParameterName] = request.ServerVariables;
                    }
                }
                else
                {
                    Type paramterType = p.ParameterType.GetRealType();

                    // 如果参数是可支持的类型,则直接从HttpRequest中读取并赋值
                    if (paramterType.IsSupportableType())
                    {
                        object val = GetValueByNameAndTypeFrommRequest(request, p.ParameterType.GetRealType(), p.ParameterName, p.BindingInfo.Prefix);
                        if (val != null)
                        {
                            parameters[p.ParameterName] = val;
                        }
                        else
                        {
                            if (p.ParameterType.IsValueType && p.ParameterType.IsNullableType() == false)
                            {
                                throw new ArgumentException("未能找到指定的参数值:" + p.ParameterName);
                            }
                        }
                    }
                    else
                    {
                        // 自定义的类型。首先创建实例,然后给所有成员赋值。
                        // 注意:这里不支持嵌套类型的自定义类型。
                        //object item = Activator.CreateInstance(paramterType);
                        object item = paramterType.GetConstructor(Type.EmptyTypes).FastCreate();
                        FillModel(request, item, p);
                        parameters[p.ParameterName] = item;
                    }
                }
            }

            return(parameters);
        }
        protected virtual IDictionary<string, object> GetParameterValues(
            ControllerContext context, ActionDescriptor descriptor)
        {
            Precondition.Require(context, () => Error.ArgumentNull("context"));
            Precondition.Require(descriptor, () => Error.ArgumentNull("descriptor"));

            return descriptor.GetParameters().ToDictionary(
                p => p.Name, p => GetParameterValue(context, p), 
                StringComparer.OrdinalIgnoreCase);
        }
Esempio n. 29
0
        /// <summary>
        /// Inject the Model &amp; Message into the parameters that will be passed to this Action (if appropriate parameters are available).
        /// </summary>
        /// <param name="controller">The controller that contains this action</param>
        /// <param name="actionDescriptor">The Action in the Controller that is going to be executed</param>
        /// <param name="model">The Model that should be passed to the Action if possible</param>
        /// <param name="message">The Message that should be passed to the Action if possible</param>
        private void PopulateActionParameters(
            ControllerBase controller,
            ActionDescriptor actionDescriptor,
            object model   = null,
            object message = null)
        {
            if (actionDescriptor.ControllerDescriptor.ControllerType != controller.GetType())
            {
                throw new ArgumentException("actionDescriptor does not describe a valid action for the controller supplied");
            }

            if (!this.HasAcceptableParameters(actionDescriptor, model, message))
            {
                throw new ArgumentException("actionDescriptor does not have valid parameters that can be populated");
            }

            // Extract the Actions Parameters
            var parameters = actionDescriptor.GetParameters();

            // Extract the parameters we're likely to be filling in
            var firstParam = actionDescriptor.GetParameters().FirstOrDefault();
            var lastParam  = actionDescriptor.GetParameters().LastOrDefault();

            // If we're expecting 1, assign either the model or message
            if (parameters.Count() == 1 && (model != null || message != null) && firstParam != null)
            {
                // If it's assignable from Model
                if (model != null && firstParam.ParameterType.IsAssignableFrom(model.GetType()))
                {
                    controller.ControllerContext.RouteData.Values[firstParam.ParameterName] = model;
                }
                else if (message != null)

                // Don't need to double check this because the HasAcceptableParameters method has already done this
                /* if (message != null && firstParam.ParameterType.IsAssignableFrom(message.GetType())) */
                {
                    controller.ControllerContext.RouteData.Values[firstParam.ParameterName] = message;
                }
            }

            // If we're expecting 2, assign both the correct way round
            else if (parameters.Count() == 2 && model != null && message != null && firstParam != null &&
                     lastParam != null)
            {
                if (
                    firstParam.ParameterType.IsAssignableFrom(model.GetType()) &&
                    lastParam.ParameterType.IsAssignableFrom(message.GetType()))
                {
                    controller.ControllerContext.RouteData.Values[firstParam.ParameterName] = model;
                    controller.ControllerContext.RouteData.Values[lastParam.ParameterName]  = message;
                }
                else

                // Don't need to double check this because the HasAcceptableParameters method has already done this

                /*
                 *  if (
                 *  firstParam.ParameterType.IsAssignableFrom(message.GetType()) &&
                 *  lastParam.ParameterType.IsAssignableFrom(model.GetType()))
                 */
                {
                    controller.ControllerContext.RouteData.Values[firstParam.ParameterName] = message;
                    controller.ControllerContext.RouteData.Values[lastParam.ParameterName]  = model;
                }
            }
        }