Beispiel #1
0
        private static void AutoRegisterRoutes(
            IMvcApplication application,
            IServerRoutingTable serverRoutingTable,
            IServiceProvider serviceProvider)
        {
            var controllers = application
                              .GetType()
                              .Assembly
                              .GetTypes()
                              .Where(type =>
                                     type.IsClass &&
                                     !type.IsAbstract &&
                                     typeof(Controller).IsAssignableFrom(type));

            foreach (var controllerType in controllers)
            {
                var actions = controllerType
                              .GetMethods(
                    BindingFlags.DeclaredOnly |
                    BindingFlags.Public |
                    BindingFlags.Instance)
                              .Where(m => !m.IsSpecialName && m.DeclaringType == controllerType)
                              .Where(x => x.GetCustomAttributes().All(a => a.GetType() != typeof(NonActionAttribute)));

                foreach (var action in actions)
                {
                    var path = $"/{controllerType.Name.Replace("Controller", string.Empty)}/{action.Name}";

                    var attribute = action
                                    .GetCustomAttributes()
                                    .Where(x => x
                                           .GetType()
                                           .IsSubclassOf(typeof(BaseHttpAttribute)))
                                    .LastOrDefault() as BaseHttpAttribute;

                    var httpMethod = HttpRequestMethod.Get;

                    if (attribute != null)
                    {
                        httpMethod = attribute.Method;
                    }

                    if (attribute?.Url != null)
                    {
                        path = attribute.Url;
                    }

                    if (attribute?.ActionName != null)
                    {
                        path = $"/{controllerType.Name.Replace("Controller", string.Empty)}/{attribute.ActionName}";
                    }

                    serverRoutingTable.Add(httpMethod, path,
                                           (request) => ProcessRequest(serviceProvider, controllerType, action, request));

                    Console.WriteLine(httpMethod + " " + path);
                }
            }
        }
Beispiel #2
0
        private static IHttpResponse ProccessRequest(
            DependencyContainer.IServiceProvider serviceProvider,
            Type controllerType,
            MethodInfo action,
            IHttpRequest request)
        {
            var controllerInstance = serviceProvider.CreateInstance(controllerType) as Controller;

            controllerState.SetState(controllerInstance);
            controllerInstance.Request = request;
            var controllerPrincipal = (controllerInstance).User;
            var authorizeAttribute  = action.GetCustomAttributes()
                                      .LastOrDefault(a => a.GetType() == typeof(AuthorizeAttribute)) as AuthorizeAttribute;

            if (authorizeAttribute != null && !authorizeAttribute.IsInAuthority(controllerPrincipal))
            {
                return(new HttpResponse(HttpResponseStatusCode.Forbidden));
            }

            var parameters      = action.GetParameters();
            var parameterValues = new List <object>();

            foreach (var parameter in parameters)
            {
                ISet <string> httpDataValue = TryGetHttpParameter(request, parameter.Name);

                if (parameter.ParameterType.GetInterfaces().Any(x =>
                                                                x.IsGenericType &&
                                                                x.GetGenericTypeDefinition() == typeof(IEnumerable <>)))
                {
                    var collection = httpDataValue.Select(x => Convert.ChangeType(x, parameter.ParameterType.GenericTypeArguments.First()));
                    parameterValues.Add(collection);
                    continue;
                }

                try
                {
                    var httpStringValue = httpDataValue.FirstOrDefault();
                    var parameterValue  = Convert.ChangeType(httpStringValue, parameter.ParameterType);
                    parameterValues.Add(parameterValue);
                }
                catch
                {
                    var paramaterValue = Activator.CreateInstance(parameter.ParameterType);
                    var properties     = parameter.ParameterType.GetProperties();

                    foreach (var property in properties)
                    {
                        ISet <string> propertyHttpDataValue = TryGetHttpParameter(request, property.Name);

                        if (property.PropertyType
                            .GetInterfaces()
                            .Any(x => x.IsGenericType &&
                                 x.GetGenericTypeDefinition() == typeof(IEnumerable <>) &&
                                 property.PropertyType != typeof(string)))
                        {
                            var propertyValue = (IList <string>)Activator.CreateInstance(property.PropertyType);

                            foreach (var parameterElement in propertyHttpDataValue)
                            {
                                propertyValue.Add(parameterElement);
                            }

                            property.SetMethod.Invoke(paramaterValue, new object[] { propertyValue });
                        }
                        else
                        {
                            var firstValue    = propertyHttpDataValue.First();
                            var propertyValue = Convert.ChangeType(firstValue, property.PropertyType);

                            property.SetMethod.Invoke(paramaterValue, new object[] { propertyValue });
                        }
                    }

                    if (request.RequestMethod == HttpRequestMethod.Post)
                    {
                        controllerState.Reset();
                        controllerInstance.ModelState = ValidateObject(paramaterValue);
                        controllerState.Initialize(controllerInstance);
                    }

                    parameterValues.Add(paramaterValue);
                }
            }

            var responce = action.Invoke(controllerInstance, parameterValues.ToArray()) as IHttpResponse;

            return(responce);
        }
Beispiel #3
0
        private static void AutoRegisterRoutes(IMvcApplication startUp
                                               , IServerRoutingTable serverRoutingTable
                                               , DependencyContainer.IServiceProvider serviceProvider)
        {
            Assembly applicationAssembly = startUp.GetType().Assembly;

            Type[] controllers = applicationAssembly.GetTypes()
                                 .Where(t => typeof(Controller).IsAssignableFrom(t)).ToArray();

            foreach (var controller in controllers)
            {
                MethodInfo[] actions = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance
                                                             | BindingFlags.DeclaredOnly)
                                       .Where(m => m.IsSpecialName == false && m.GetCustomAttribute <NonActionAttribute>() == null).ToArray();
                foreach (var method in actions)
                {
                    BaseHttpAttribute httpAttribute = (BaseHttpAttribute)method
                                                      .GetCustomAttributes()
                                                      .Where(a => typeof(BaseHttpAttribute).IsAssignableFrom(a.GetType()))
                                                      .LastOrDefault();

                    string folderName = controller.Name.Replace("Controller", string.Empty);
                    string actionName = method.Name;

                    string url = $"/{folderName}/{actionName}";

                    HttpRequestMethod httpRequestMethod = HttpRequestMethod.Get;

                    if (httpAttribute != null)
                    {
                        httpRequestMethod = httpAttribute.HttpRequestMethod;

                        if (!string.IsNullOrWhiteSpace(httpAttribute.Url))
                        {
                            url = httpAttribute.Url;
                        }
                        if (!string.IsNullOrWhiteSpace(httpAttribute.ActionName))
                        {
                            actionName = httpAttribute.ActionName;
                            url        = $"/{folderName}/{actionName}";
                        }
                    }

                    serverRoutingTable.Add(httpRequestMethod, url, (request)
                                           =>
                    {
                        var controllerInstance = serviceProvider.CreateInstance(controller) as Controller;
                        controllerState.SetStateOfController(controllerInstance);
                        controllerInstance.Request            = request;
                        AuthorizeAttribute authorizeAttribute = method.GetCustomAttribute <AuthorizeAttribute>();
                        if (authorizeAttribute != null &&
                            !authorizeAttribute.IsAuthorized(controllerInstance.User))
                        {
                            return(new RedirectResult("/"));
                        }

                        var parametersInfos     = method.GetParameters();
                        var parametersInstances = new List <object>();

                        foreach (var parameterInfo in parametersInfos)
                        {
                            var parameterName = parameterInfo.Name;
                            var parameterType = parameterInfo.ParameterType;

                            var parameterValue             = GetValue(request, parameterName) as ISet <string>;
                            object parameterValueConverted = null;
                            try
                            {
                                if (parameterValue == null)   // NOT FOUND AND COMPLEX TYPE
                                {
                                    throw new Exception();
                                }

                                if (parameterValue.Count == 1)   // SIMPLE TYPE
                                {
                                    parameterValueConverted = Convert.ChangeType(parameterValue.First(), parameterType);
                                }
                                else   // COLLECTION
                                {
                                    parameterValueConverted = parameterValue.Select(parameter =>
                                    {
                                        Type[] genericArguments = parameterType.GetGenericArguments();
                                        Type conversionType     = genericArguments[0];
                                        return(Convert.ChangeType(parameter, conversionType));
                                    }).ToList();

                                    var instanceOfCollection = Activator.CreateInstance(typeof(List <>)
                                                                                        .MakeGenericType(parameterType.GetGenericArguments()[0]))
                                                               as IList;

                                    foreach (var item in parameterValueConverted as List <object> )
                                    {
                                        instanceOfCollection.Add(item);
                                    }

                                    parameterValueConverted = instanceOfCollection;
                                }
                            }
                            catch (Exception)
                            {
                                if (parameterType.GetInterface("IEnumerable") == null)
                                {
                                    parameterValueConverted = Activator.CreateInstance(parameterType);
                                    foreach (var property in parameterType.GetProperties())
                                    {
                                        var propertyValueFromRequest             = GetValue(request, property.Name) as ISet <string>;
                                        object propertyValueFromRequestConverted = null;
                                        if (propertyValueFromRequest == null)
                                        {
                                        }
                                        else if (propertyValueFromRequest.Count == 1)
                                        {
                                            propertyValueFromRequestConverted = Convert.ChangeType(propertyValueFromRequest.First(), property.PropertyType);
                                        }
                                        else
                                        {
                                            propertyValueFromRequestConverted = propertyValueFromRequest.Select(parameter =>
                                            {
                                                Type[] genericArguments = property.PropertyType.GetGenericArguments();
                                                Type conversionType     = genericArguments[0];
                                                return(Convert.ChangeType(parameter, conversionType));
                                            }).ToList();

                                            var instanceOfCollection = Activator.CreateInstance(typeof(List <>)
                                                                                                .MakeGenericType(property.PropertyType.GetGenericArguments()[0]))
                                                                       as IList;

                                            foreach (var item in propertyValueFromRequestConverted as List <object> )
                                            {
                                                instanceOfCollection.Add(item);
                                            }

                                            propertyValueFromRequestConverted = instanceOfCollection;
                                        }
                                        property.SetValue(parameterValueConverted, propertyValueFromRequestConverted);
                                    }
                                }
                            }

                            if (httpRequestMethod == HttpRequestMethod.Post)
                            {
                                controllerInstance.ModelState = ValidateObject(parameterValueConverted);
                                controllerState.InitializeInnerState(controllerInstance);
                            }


                            parametersInstances.Add(parameterValueConverted);
                        }

                        var response = method.Invoke(controllerInstance, parametersInstances.ToArray());

                        if (httpRequestMethod == HttpRequestMethod.Get)
                        {
                            controllerState.Reset();
                        }
                        return(response as IHttpResponse);
                    });
                }
            }
        }