public static async Task CreateHostAsync(IMvcAplication app, int port = 80) { List <Route> routeTable = new List <Route>(); IServiceCollection serviceCollection = new ServiceCollection(); app.Configure(routeTable); app.ConfigureServices(serviceCollection); AutoRegisterStaticFile(routeTable); AutoRegisterRoutes(routeTable, app, serviceCollection); IHttpServer server = new HttpServer(routeTable); await server.StartAsync(port); }
private static void AutoRegisterRoutes(List <Route> routeTable, IMvcAplication app, IServiceCollection serviceCollection) { var controllerTypes = app.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.DeclaringType == controllerType && !x.IsStatic && !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))); } } }