private static void AutoRegisterRoutes(ServerRoutingTable table, IMvcApplication application, IServiceCollection serviceCollection) { //Get all controllers var controllers = application.GetType().Assembly.GetTypes().Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof(Controller))); //Go through all the controllers foreach (var controller in controllers) { //Take all the methods of every controller var getMethods = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(method => method.CustomAttributes.Any(ca => ca.AttributeType.IsSubclassOf(typeof(HttpAttribute)))); //Go trough all the methods of the controller foreach (var methodInfo in getMethods) { //Get the custom HttpAttribute of the method GET or POST (for now...) var httpAttribute = (HttpAttribute)methodInfo.GetCustomAttributes(true).FirstOrDefault(x => x.GetType().IsSubclassOf(typeof(HttpAttribute))); if (httpAttribute == null) { continue; } //Add to the routing table (HttpMethod (from the HttpAttribute), the path (from the HttpAttribute) and Invoke a specific Action that accepts Request and returns a Response) table.Add(httpAttribute.Mehtod, httpAttribute.Path, (request) => ExecuteAction(controller, methodInfo, request, serviceCollection)); } } }
private static void AutoRegisterRoutes(ServerRoutingTable routingTable, IMvcApplication application, IServiceCollection serviceCollection) { var controllers = application.GetType().Assembly.GetTypes() .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(Controller))); foreach (Type controller in controllers) { MethodInfo[] getMethods = (MethodInfo[])controller.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where( method => method.CustomAttributes.Any( ca => ca.AttributeType.IsSubclassOf(typeof(HttpAttribute)))).ToArray(); foreach (MethodInfo methodInfo in getMethods) { HttpAttribute httpAttribute = (HttpAttribute)methodInfo.GetCustomAttributes(true) .FirstOrDefault(ca => ca.GetType().IsSubclassOf(typeof(HttpAttribute))); if (httpAttribute == null) { continue; } routingTable.Add(httpAttribute.Method, httpAttribute.Path, (request) => ExecuteAction(controller, methodInfo, request, serviceCollection)); Console.WriteLine($"{controller.Name}=>{methodInfo.Name}=>{httpAttribute.Method}=>{httpAttribute.Path}"); } } }
private static void AutoRegisterRoutes(IMvcApplication application, IServerRoutingTable serverRoutingTable) { var controllers = application.GetType().Assembly.GetTypes().Where(type => type.IsClass && !type.IsAbstract && typeof(Controller).IsAssignableFrom(type)); foreach (var controllerType in controllers) { //TODO: Remove ToString from Info Controller var actions = controllerType .GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) .Where(x => !x.IsSpecialName && x.DeclaringType == controllerType) .Where(x => x.GetCustomAttributes().All(a => a.GetType() != typeof(NonActionAttribute))); foreach (var action in actions) { string 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 => { var controllerInstance = Activator.CreateInstance(controllerType); ((Controller)controllerInstance).Request = request; var controllerPrincipal = ((Controller)controllerInstance).User; //Security Authorization TODO: refactor this var authorizeAttribute = action.GetCustomAttributes().LastOrDefault(a => a.GetType() == typeof(AuthorizeAttribute)) as AuthorizeAttribute; if (authorizeAttribute != null && !authorizeAttribute.IsInAuthority(controllerPrincipal)) { //TODO: redirect to configured Url return(new HttpResponse(HttpResponseStatusCode.Forbidden)); } var response = action.Invoke(controllerInstance, new object[0]) as ActionResult; return(response); }); } } }
public static async Task RunAsync(IMvcApplication application, int port) { ServerRoutingTable = new ServerRoutingTable(); IServiceCollection serviceCollection = new ServiceCollection(); application.ConfigureServices(serviceCollection); application.Configure(ServerRoutingTable); ServerRoutingTable .LoadControllers(application.GetType().Assembly, serviceCollection) .LoadStaticFiles(); Console.WriteLine(string.Join(Environment.NewLine, ServerRoutingTable.GetAllRouteNames())); TcpListener listener = new TcpListener(IPAddress.Parse(LocalhostIpAddress), port); listener.Start(); IsRunning = true; Console.WriteLine($"Server started at http://{LocalhostIpAddress}:{port}"); while (IsRunning) { Console.WriteLine("Waiting for client..."); var client = await listener.AcceptSocketAsync(); ListenAsync(client); } }
// /{controller}/{action}/ private static void AutoRegisterActionRoutes(IList <Route> routeTable, IMvcApplication application, IServiceCollection serviceCollection) { var controllers = application.GetType().Assembly.GetTypes() .Where(type => type.IsSubclassOf(typeof(Controller)) && !type.IsAbstract); foreach (var controller in controllers) { var actions = controller.GetMethods() .Where(x => !x.IsSpecialName && !x.IsConstructor && x.IsPublic && x.DeclaringType == controller); foreach (var action in actions) { string url = "/" + controller.Name.Replace("Controller", string.Empty) + "/" + action.Name; var attribute = action.GetCustomAttributes() .FirstOrDefault(x => x.GetType() .IsSubclassOf(typeof(HttpMethodAttribute))) as HttpMethodAttribute; var httpActionType = HttpMethodType.Get; if (attribute != null) { httpActionType = attribute.Type; if (attribute.Url != null) { url = attribute.Url; } } routeTable.Add(new Route(httpActionType, url, (request) => InvokeAction(request, serviceCollection, controller, action))); } } }
private static void AutoRegisterRoutes(List <Route> routeTable, IMvcApplication application, IServiceCollection serviceCollection) { var controllerTypes = application.GetType().Assembly.GetTypes() .Where(x => x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof(Controller))); foreach (var controllerType in controllerTypes) { var methods = controllerType.GetMethods() .Where(x => x.IsPublic && !x.IsStatic && x.DeclaringType == controllerType && !x.IsAbstract && !x.IsConstructor && !x.IsSpecialName); foreach (var method in methods) { var url = "/" + controllerType.Name.Replace("Controller", string.Empty) + "/" + method.Name; var attribute = method.GetCustomAttributes(false) .Where(x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))) .FirstOrDefault() as BaseHttpAttribute; var httpMethod = HttpMethod.Get; if (attribute != null) { httpMethod = attribute.Method; } if (!string.IsNullOrEmpty(attribute?.Url)) { url = attribute.Url; } routeTable.Add(new Route(url, httpMethod, request => ExecuteAction(request, controllerType, method, serviceCollection))); } } }
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); } } }
private static void AutoRegisterRoutes( IMvcApplication application, IServerRoutingTable serverRoutingTable) { var controllers = application.GetType().Assembly.GetTypes() .Where(type => type.IsClass && !type.IsAbstract && typeof(Controller).IsAssignableFrom(type)); // TODO: RemoveToString from InfoController foreach (var controller in controllers) { var actions = controller .GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) .Where(x => !x.IsSpecialName && x.DeclaringType == controller); foreach (var action in actions) { var path = $"/{controller.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 = $"/{controller.Name.Replace("Controller", string.Empty)}/{attribute.ActionName}"; } serverRoutingTable.Add(httpMethod, path, request => { // request => new UsersController().Login(request) var controllerInstance = Activator.CreateInstance(controller); var response = action.Invoke(controllerInstance, new[] { request }) as IHttpResponse; return(response); }); Console.WriteLine(httpMethod + " " + path); } } // Reflection // Assembly // typeof(Server).GetMethods() // sb.GetType().GetMethods(); // Activator.CreateInstance(typeof(Server)) var sb = DateTime.UtcNow; }
private static void AutoRegisterRoutes(IMvcApplication application, IServerRoutingTable serverRoutingTable) { 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(x => !x.IsSpecialName && x.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 => { var controllerInstance = Activator.CreateInstance(controllerType); var response = action.Invoke(controllerInstance, new [] { request }) as IHttpResponse; return(response); }); Console.WriteLine(httpMethod + " " + path); } } Console.WriteLine(string.Join(Environment.NewLine, serverRoutingTable)); }
private static void AutoRegisterRoutes(List <Route> routeTable, IMvcApplication application, IServiceCollection serviceCollection) { //routeTable.Add(new Route("/cards/add", HttpMethod.Get, new CardsController().Add)); var controllerTypes = application.GetType().Assembly.GetTypes() .Where(x => !x.IsAbstract && x.IsClass && x.IsSubclassOf(typeof(Controller))); //we want only the Controller sub-classes //Get the methods of each controller foreach (var controllerType in controllerTypes) { //With the current methods, even only x.DeclaringType == controllerType will do the job. var methods = controllerType.GetMethods() .Where(x => x.IsPublic && !x.IsStatic && x.DeclaringType == controllerType && !x.IsAbstract && !x.IsConstructor && !x.IsSpecialName); //For testing purpose //Console.WriteLine(controllerType.Name); foreach (var method in methods) { var url = ($"/{controllerType.Name.Replace("Controller", string.Empty).ToLower()}/{method.Name.ToLower()}"); //Console.WriteLine(url); //SUS.MvcFramework.HttpGetAttribute / HttpPostAttribute var customAttribute = method.GetCustomAttributes(false) .Where(x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))) .FirstOrDefault() as BaseHttpAttribute; var httpMethod = HttpMethod.Get; //Check if we've set custom url to the attribute [HttpPost("custom url")] if (!string.IsNullOrWhiteSpace(customAttribute?.Url)) { url = customAttribute.Url; } //Check if method is Get or Post if (customAttribute != null) { httpMethod = customAttribute.Method; } if (!string.IsNullOrEmpty(customAttribute?.Url)) { url = customAttribute.Url; } //We can afford to cast to HttpResponse since every action returns httpresponse. In ASP Core it will return IActionResult routeTable.Add(new Route(url, httpMethod, request => ExecuteAction(request, controllerType, method, serviceCollection))); } } }
private static void AutoRegisterRoutes(IMvcApplication application, IServerRoutingTable serverRoutingTable, IServiceProvider serviceProvider, RouteSettings routeSettings) { IEnumerable <System.Type> controllers = application.GetType().Assembly .GetTypes() .Where(type => type.IsClass && !type.IsAbstract && typeof(Controller).IsAssignableFrom(type)); foreach (var controllerType in controllers) { IEnumerable <MethodInfo> actions = controllerType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) .Where(m => !m.IsSpecialName && !m.IsVirtual && m.GetCustomAttribute <NonActionAttribute>() == null); string controllerName = controllerType.Name.Replace("Controller", ""); AuthorizeAttribute controllerAuthorizeAttribute = controllerType.GetCustomAttribute <AuthorizeAttribute>() as AuthorizeAttribute; foreach (var action in actions) { string path = $"/{controllerName}/{action.Name}"; BaseHttpAttribute attribute = action.GetCustomAttributes() .LastOrDefault(a => a.GetType().IsSubclassOf(typeof(BaseHttpAttribute))) as BaseHttpAttribute; HttpRequestMethod requestMethod = HttpRequestMethod.Get; if (attribute != null) { requestMethod = attribute.HttpRequestMethod; } if (attribute?.ActionName != null) { path = $"/{controllerName}/{attribute.ActionName}"; } if (attribute?.Url != null) { path = attribute.Url; } serverRoutingTable.Add(requestMethod, path, request => { return(ProcessRequest(serviceProvider, request, controllerType, controllerAuthorizeAttribute, action, routeSettings)); }); } } }
private static void AutoRegisterRoutes(List <Route> routeTable, IMvcApplication application) { // routeTable.Add(new Route("/cards/all", HttpMethod.Get, new CardsController().All)); var controllerTypes = application.GetType().Assembly.GetTypes() .Where(x => x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof(Controller))); foreach (var controllerType in controllerTypes) { Console.WriteLine(controllerType.Name); var methods = controllerType.GetMethods() .Where(x => x.IsPublic && !x.IsStatic && x.DeclaringType == controllerType && !x.IsAbstract && !x.IsConstructor && !x.IsSpecialName); foreach (var method in methods) { var url = "/" + controllerType.Name.Replace("Controller", string.Empty) + "/" + method.Name; url = url.ToLower(); var attribute = method.GetCustomAttributes(false).Where(x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))) .FirstOrDefault() as BaseHttpAttribute; var httpMethod = HttpMethod.Get; if (attribute != null) { httpMethod = attribute.Method; } if (!string.IsNullOrEmpty(attribute?.Url)) { url = attribute.Url; } routeTable.Add(new Route(url, httpMethod, (request) => { var instance = Activator.CreateInstance(controllerType) as Controller; instance.Request = request; var response = method.Invoke(instance, new object[] { }) as HttpResponse; return(response); })); Console.WriteLine(" - " + url); } } }
private static void AutoRegisterRoutes(List <Route> routeTable, IMvcApplication application, IServiceCollection serviceCollection) { //routeTable.Add(new Route("/users/register", HttpMethod.Get, new UsersController().Register)); var controllerTypes = application .GetType().Assembly.GetTypes().Where(x => x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof(Controller))); foreach (var controllerType in controllerTypes) { Console.WriteLine(controllerType.Name); //iskam samo methodite, koito naricham actions v edno MVC, t.e. krajni destinacii za potrebitelski zaqwki!! var methods = controllerType.GetMethods() .Where(x => x.IsPublic && !x.IsStatic && x.DeclaringType == controllerType && //samo methods, kojto sa declarirani v syotvetniq controller class iskam, ne v base classa mu! !x.IsAbstract && !x.IsConstructor && //ne e constructor method !x.IsSpecialName); //ne e get ili set method na property!!! te sa s imena get_PropertyName i set_Propertyname, ne gi iskam! foreach (var method in methods) { var url = "/" + controllerType.Name.Replace("Controller", string.Empty) + "/" + method.Name; var attribute = method .GetCustomAttributes(false) .FirstOrDefault(x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))) as BaseHttpAttribute; var httpMethod = HttpMethod.Get; if (attribute != null) { httpMethod = attribute.Method; } if (!string.IsNullOrEmpty(attribute?.Url)) { url = attribute.Url; } routeTable.Add(new Route(url, httpMethod, (request) => ExecuteAction(serviceCollection, controllerType, method, request))); Console.WriteLine($" - {method.Name}"); } } }
private static void AutoRegisterRoutes(IMvcApplication application, IServerRoutingTable serverRoutingTable) { //todo refactoring var controllers = application.GetType().Assembly.GetTypes().Where(type => type.IsClass && !type.IsAbstract && typeof(Controller).IsAssignableFrom(type)); foreach (var controller in controllers) { var actions = controller.GetMethods( BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance ).Where(type => type.DeclaringType == controller && !type.IsSpecialName); foreach (var methodInfo in actions) { var path = ($"/{controller.Name.Replace("Controller", "")}/{methodInfo.Name}"); var attribute = methodInfo.GetCustomAttributes().Where( x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))).LastOrDefault() as BaseHttpAttribute; // Console.WriteLine(attribute?.AttributeType.Name); var httpMethod = HttpRequestMethod.Get; if (attribute != null) { httpMethod = attribute.Method; } if (attribute?.Url != null) { path = attribute.Url; } if (attribute?.ActionName != null) { path = ($"/{controller.Name.Replace("Controller", "")}/{attribute.ActionName}"); } serverRoutingTable.Add(httpMethod, path, request => { var controllerInstance = Activator.CreateInstance(controller); var response = methodInfo.Invoke(controllerInstance, new[] { request }) as IHttpResponse; return(response); }); Console.WriteLine(httpMethod + " " + path); } } }
private static void AutoRegisterNonStaticFilesRoute(List <Route> routeTable, IMvcApplication application) { var types = application.GetType().Assembly.GetTypes() .Where(type => type.IsSubclassOf(typeof(Controller)) && !type.IsAbstract); foreach (var type in types) { Console.WriteLine(type.FullName); var methods = type.GetMethods() .Where(x => !x.IsSpecialName && !x.IsConstructor && x.IsPublic && x.DeclaringType == type); foreach (var method in methods) { string url = "/" + type.Name.Replace("Controller", string.Empty) + "/" + method.Name; var attribute = method.GetCustomAttributes() .FirstOrDefault(x => x.GetType() .IsSubclassOf(typeof(HttpMethodAttribute))) as HttpMethodAttribute; var httpActionType = HttpMethodType.Get; if (attribute != null) { httpActionType = attribute.Type; if (attribute.Url != null) { url = attribute.Url; } } routeTable.Add(new Route(url, httpActionType, (request) => { var controller = Activator.CreateInstance(type) as Controller; controller.Request = request; var response = method.Invoke(controller, new object [] {}) as HttpResponse; return(response); })); Console.WriteLine(" " + url); } } }
private static void AutoRegisterRoutes(List <Route> routeTable, IMvcApplication application) { var controllerTypes = application.GetType().Assembly.GetTypes() .Where(x => x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof(Controller))); foreach (var controllerType in controllerTypes) { var methods = controllerType.GetMethods() .Where(x => x.IsPublic && !x.IsStatic && x.DeclaringType == controllerType && !x.IsAbstract && !x.IsConstructor && !x.IsSpecialName); foreach (var method in methods) { var url = "/" + controllerType.Name.Replace("Controller", string.Empty) + "/" + method.Name; var attribute = method.GetCustomAttributes(false) .Where(x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))) .FirstOrDefault() as BaseHttpAttribute; var httpMethod = HttpMethod.Get; if (attribute != null) { httpMethod = attribute.Method; } if (!string.IsNullOrEmpty(attribute?.Url)) { url = attribute.Url; } // AutoRegisterRoutes() на практика създава route-ове от наличните контролери (по папките) routeTable.Add(new Route(url, httpMethod, (request) => // тук задаваме автоматично всеки route, който ще се изпълни в HTTPServer-a само при request на съответния path (тук не се изпълнява) { var instance = Activator.CreateInstance(controllerType) as Controller; instance.Request = request; var response = method.Invoke(instance, new object[] { }) as HttpResponse; return(response); })); } } }
private static void AutoRegisterRoutes(IMvcApplication application, ServerRoutingTable routingTable, IServiceCollection serviceCollection) { var controllers = application.GetType().Assembly.GetTypes() .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(Controller))); foreach (var controller in controllers) { var methods = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => m.CustomAttributes.Any(ca => ca.AttributeType.IsSubclassOf(typeof(HttpAttribute)))); foreach (var method in methods) { var httpAttribute = (HttpAttribute)method.GetCustomAttributes(true).FirstOrDefault(ca => ca.GetType().IsSubclassOf(typeof(HttpAttribute))); if (httpAttribute == null) { continue; } routingTable.Add(httpAttribute.Method, httpAttribute.Path, (request => ExecuteAction(controller, method, request, serviceCollection))); } } }
private static void AutoRegisterRoutes(ServerRoutingTable routingTable, IMvcApplication application, IServiceCollection serviceCollection) { var controllers = application.GetType().Assembly.GetTypes() .Where(x => x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof(Controller))); foreach (var controller in controllers) { var getMethods = controller .GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => m.CustomAttributes .Any(ca => ca.AttributeType.IsSubclassOf(typeof(HttpAttrubute)))); foreach (var methodInfo in getMethods) { var httpAttribute = (HttpAttrubute)methodInfo.GetCustomAttributes(true) .FirstOrDefault(ca => ca.GetType().IsSubclassOf(typeof(HttpAttrubute))); routingTable.Add(httpAttribute.Method, httpAttribute.Path, (request) => ExecuteAction(controller, methodInfo, request, serviceCollection)); Console.WriteLine($"Route registered: {controller.FullName}.{httpAttribute.Method}=> Action: {httpAttribute.Path}"); } } }
private static void RegisterActions(ServerRoutingTable routingTable, IMvcApplication application, MvcFrameworkSettings settings, IServiceCollection serviceCollection) { var userCookieService = serviceCollection.CreateInstance <IUserCookieService>(); var controllers = application.GetType().Assembly.GetTypes() .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(Controller))); foreach (var controller in controllers) { var getMethods = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (var methodInfo in getMethods) { var httpAttribute = (HttpAttribute)methodInfo.GetCustomAttributes(true) .FirstOrDefault(ca => ca.GetType().IsSubclassOf(typeof(HttpAttribute))); var method = HttpRequestMethod.GET; string path = null; if (httpAttribute != null) { method = httpAttribute.Method; path = httpAttribute.Path; } if (path == null) { var controllerName = controller.Name; if (controllerName.EndsWith("Controller")) { controllerName = controllerName.Substring(0, controllerName.Length - "Controller".Length); } var actionName = methodInfo.Name; path = $"/{controllerName.ToLower()}/{actionName.ToLower()}"; } else if (!path.StartsWith("/")) { path = "/" + path; } var authorizeAttribute = methodInfo.GetCustomAttributes(true).FirstOrDefault(ca => ca.GetType() == typeof(AuthorizeAttribute)) as AuthorizeAttribute; routingTable.Add(method, path, (request) => { if (authorizeAttribute != null) { var userData = Controller.GetUserData(request.Cookies, userCookieService); if (userData == null || !userData.IsLoggedIn || (authorizeAttribute.RoleName != null && authorizeAttribute.RoleName != userData.Role)) { var response = new HttpResponse(); response.Headers.Add(new HttpHeader(HttpHeader.Location, settings.LoginPageUrl)); response.StatusCode = HttpResponseStatusCode.SeeOther; return(response); } } return(ExecuteAction(controller, methodInfo, request, serviceCollection)); }); Console.WriteLine($"Route registered: {controller.Name}.{methodInfo.Name} => {method} => {path}"); } } }
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); }); } } }
public static void AutoRegisterMappingRoutes(IMvcApplication application, IServerRoutingTable serverRoutingTable) { //we take all of the controllers (first filter is with the name of the controllers) var controllers = application.GetType().Assembly.GetTypes() .Where(type => type.IsClass && !type.IsAbstract && typeof(Controller).IsAssignableFrom(type)); // TODO: RemoveToString from InfoController foreach (var controller in controllers) { //2nd filter is that we want only the actions var actions = controller .GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) .Where(x => !x.IsSpecialName && x.DeclaringType == controller) .Where(m => m.GetCustomAttributes().All(a => a.GetType() != typeof(NonActionAttribute))); foreach (var action in actions) { //3rd we create the path (from the controllerName and actionName) var path = $"/{controller.Name.Replace("Controller", string.Empty)}/{action.Name}"; //4th each action will have at least one attribute if it doesn`t we have to make the default settings (get) var attribute = action .GetCustomAttributes() .LastOrDefault(a => a.GetType().IsSubclassOf(typeof(BaseHttpAttribute))) as BaseHttpAttribute; var httpMethod = HttpRequestMethod.Get; //5th for post/get if (attribute != null) { httpMethod = attribute.Method; } //6th this is for "/" if (attribute?.Url != null) { path = attribute.Url; } //7th {`confirmCreate`} this is for the confirmCase, where we take the name from the attribute and replace it with the one from the method`s name if (attribute?.ActionName != null) { path = $"/{controller.Name.Replace("Controller", string.Empty)}/{attribute.ActionName}"; } serverRoutingTable.Add(httpMethod, path, request => { // request => new UsersController().Login(request) var controllerInstance = (Controller)Activator.CreateInstance(controller); //note:** on each new request, we receive a new controller instance, to which we add the request (and the session storage within the request)) controllerInstance.Request = request; //we get the principal , which is like a session object var controllerPrincipal = controllerInstance.User; //Security Authorization -> TODO: Refactor this. //note: here we take the author. attribute from the ACTION , not controller var authorizeAttribute = action.GetCustomAttributes() .LastOrDefault(a => a.GetType() == typeof(AuthorizeAttribute)) as AuthorizeAttribute; if (authorizeAttribute != null && !authorizeAttribute.IsInAuthority(controllerPrincipal)) { //note: ****so for the method/action to go through the validation, he needs both Authorization attribute (default is good) and //present principal (singed in) // TODO: Redirect to configured URL return(new HttpResponse(HttpResponseStatusCode.Forbidden)); } //TODO: Redirect to configured URL! //8th because of the conversion below, it knows what the action is i think? var response = action.Invoke(controllerInstance, new object[0]) as ActionResult; return(response); }); Console.WriteLine(httpMethod + " " + path); } } ; // Reflection // Assembly // typeof(Server).GetMethods() // sb.GetType().GetMethods(); // Activator.CreateInstance(typeof(Server)) var sb = DateTime.UtcNow; }
private static void RegisterActions( ServerRoutingTable routingTable, IMvcApplication application, MvcFrameworkSettings settings, IServiceCollection serviceCollection) { var userCookieService = serviceCollection.CreateInstance <IUserCookieService>(); var controllers = application.GetType().Assembly.GetTypes() .Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof(Controller))); foreach (var controller in controllers) { var getMethods = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (var methodInfo in getMethods) { var httpAttribute = (HttpAttribute) methodInfo .GetCustomAttributes(true) .FirstOrDefault(ca => ca.GetType().IsSubclassOf(typeof(HttpAttribute))); var method = HttpRequestMethod.Get; string path = null; if (httpAttribute != null) { path = httpAttribute.Path; method = httpAttribute.Method; } if (path == null) { //If path is null => generate path from controller and action /ControllerName/ActionName var controllerName = controller.Name; if (controllerName.EndsWith("Controller")) { controllerName = controllerName.Substring(0, controllerName.Length - "Controller".Length); } var actionName = methodInfo.Name; path = $"/{controllerName}/{actionName}"; } else if (!path.StartsWith("/")) { path = "/" + path; } var hasAuthorizeAttribute = methodInfo .GetCustomAttributes(true) .Any(ca => ca.GetType() == typeof(AuthorizeAttribute)); routingTable.Add(method, path, (request) => { // if (method has AuthorizeAttribute) if (hasAuthorizeAttribute) { //get username Controller.GetUserData var userData = Controller.GetUserData(request.Cookies, userCookieService); // check if user is logged if (userData == null) { //if not redirect to login page var response = new HttpResponse(); response.Headers.Add(new HttpHeader(HttpHeader.Location, settings.LoginPageUrl)); response.StatusCode = HttpResponseStatusCode.SeeOther; return(response); } } return(ExecuteAction(controller, methodInfo, request, serviceCollection)); }); Console.WriteLine($"Route registered:{controller.Name} {methodInfo.Name} => {method} => {path}"); } } }