예제 #1
0
        private bool TryBindFromUri(HttpControllerContext controllerContext, ParameterSwapInfo found, out HttpActionDescriptor method)
        {
            var requestParam = HttpUtility.ParseQueryString(controllerContext.Request.RequestUri.Query).Get(found.ParamName);

            requestParam = (requestParam == null) ? null : requestParam.Trim();
            var paramTypes = found.SupportedTypes;

            if (requestParam == string.Empty && paramTypes.Length > 0)
            {
                //if it's empty then in theory we can select any of the actions since they'll all need to deal with empty or null parameters
                //so we'll try to use the first one available
                method = MatchByType(paramTypes[0], controllerContext, found);
                if (method != null)
                {
                    return(true);
                }
            }

            if (requestParam != null)
            {
                foreach (var paramType in paramTypes)
                {
                    //check if this is IEnumerable and if so this will get it's type
                    //we need to know this since the requestParam will always just be a string
                    var enumType = paramType.GetEnumeratedType();

                    var converted = requestParam.TryConvertTo(enumType ?? paramType);
                    if (converted)
                    {
                        method = MatchByType(paramType, controllerContext, found);
                        if (method != null)
                        {
                            return(true);
                        }
                    }
                }
            }

            method = null;
            return(false);
        }
예제 #2
0
        private static ReflectedHttpActionDescriptor MatchByType(Type idType, HttpControllerContext controllerContext, ParameterSwapInfo found)
        {
            var controllerType = controllerContext.Controller.GetType();
            var methods        = controllerType.GetMethods().Where(info => info.Name == found.ActionName).ToArray();

            if (methods.Length > 1)
            {
                //choose the one that has the parameter with the T type
                var method = methods.FirstOrDefault(x => x.GetParameters().FirstOrDefault(p => p.Name == found.ParamName && p.ParameterType == idType) != null);

                return(new ReflectedHttpActionDescriptor(controllerContext.ControllerDescriptor, method));
            }
            return(null);
        }