コード例 #1
0
ファイル: Middleware.cs プロジェクト: encratite/BeRated
        private object Invoke(string method, Dictionary <string, string> arguments, out Type modelType, out RenderMethod renderMethod)
        {
            var notFoundException = new MiddlewareException("No such method.");
            var methodInfo        = _Instance.GetType().GetMethod(method, BindingFlags.Instance | BindingFlags.Public);

            if (methodInfo == null)
            {
                throw notFoundException;
            }
            var attribute = methodInfo.GetCustomAttribute <ControllerAttribute>();

            if (attribute == null)
            {
                throw notFoundException;
            }
            renderMethod = attribute.RenderMethod;
            var parameters       = methodInfo.GetParameters();
            var invokeParameters = new List <object>();

            foreach (var parameter in parameters)
            {
                string argument;
                object convertedParameter;
                var    type       = parameter.ParameterType;
                bool   isNullable = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>);
                if (arguments.TryGetValue(parameter.Name, out argument))
                {
                    if (isNullable)
                    {
                        type = type.GenericTypeArguments.First();
                    }
                    convertedParameter = Convert.ChangeType(argument, type);
                }
                else
                {
                    if (type == typeof(string) || isNullable)
                    {
                        convertedParameter = null;
                    }
                    else
                    {
                        string message = string.Format("Parameter \"{0}\" has not been specified.", parameter.Name);
                        throw new MiddlewareException(message);
                    }
                }
                invokeParameters.Add(convertedParameter);
            }
            var output = methodInfo.Invoke(_Instance, invokeParameters.ToArray());

            modelType = methodInfo.ReturnType;
            return(output);
        }