/// <summary> /// Load all the WebApi Controllers in an assembly. /// </summary> /// <param name="apiModule">The Web API Module instance.</param> /// <param name="assembly">The assembly to load WebApi Controllers from. Leave null to load from the currently executing assembly.</param> /// <returns>The webserver instance.</returns> /// <exception cref="System.ArgumentNullException">webserver</exception> public static WebApiModule LoadApiControllers(this WebApiModule apiModule, Assembly assembly = null) { if (apiModule == null) { throw new ArgumentNullException(nameof(apiModule)); } var types = (assembly ?? Assembly.GetEntryAssembly()).GetTypes(); var apiControllers = types.Where(x => x.GetTypeInfo().IsClass && !x.GetTypeInfo().IsAbstract && x.GetTypeInfo().IsSubclassOf(typeof(WebApiController))).ToArray(); if (!apiControllers.Any()) { return(apiModule); } foreach (var apiController in apiControllers) { apiModule.RegisterController(apiController); } return(apiModule); }
public void FluentLoadApiControllersWebApiModuleArgumentException() { WebApiModule webApi = null; Assert.Throws <ArgumentNullException>(() => { Extensions.LoadApiControllers(webApi); }); }
public void Start() { WebApiModule module = new WebApiModule(); Task.Run(() => module.StartAsync()); System.Console.WriteLine(" WebApi is started."); }
public static Task StartServer(int port) { var server = new WebServer($"http://localhost:{port}/", RoutingStrategy.Regex); WebApiModule apiModule = new WebApiModule(); apiModule.RegisterController <MeshController>(); server.RegisterModule(apiModule); return(server.RunAsync()); }
/// <summary> /// Creates an instance of <see cref="WebApiModule"/> using the default response serializer /// and adds it to a module container, giving it the specified <paramref name="name"/> /// if not <see langword="null"/> /// </summary> /// <typeparam name="TContainer">The type of the module container.</typeparam> /// <param name="this">The <typeparamref name="TContainer"/> on which this method is called.</param> /// <param name="name">The name.</param> /// <param name="baseRoute">The base route of the module.</param> /// <param name="configure">A callback used to configure the newly-created <see cref="WebApiModule"/>.</param> /// <returns><paramref name="this"/> with a <see cref="RoutingModule"/> added.</returns> /// <exception cref="NullReferenceException"><paramref name="this"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="configure"/> is <see langword="null"/>.</exception> /// <seealso cref="WebApiModule"/> /// <seealso cref="WebApiModuleExtensions"/> /// <seealso cref="IWebModuleContainer.Modules"/> /// <seealso cref="IComponentCollection{T}.Add"/> public static TContainer WithWebApi <TContainer>( this TContainer @this, string?name, string baseRoute, Action <WebApiModule> configure) where TContainer : class, IWebModuleContainer { configure = Validate.NotNull(nameof(configure), configure); var module = new WebApiModule(baseRoute); return(WithModule(@this, name, module, configure)); }
public override void Start() { Logger.NoLogging(); Instances.Add(State, this); _serverSource = new CancellationTokenSource(); _server = new WebServer(ServerUri); var webApiModule = new WebApiModule("/"); _server.WithModule(webApiModule); AdaptModule(webApiModule); _server.WithEmbeddedResources("/", Assembly.GetExecutingAssembly(), $"SpotifyAPI.Web.Auth.Resources.{_folder}"); _ = _server.RunAsync(_serverSource.Token); }
/// <summary> /// Load all the WebApi Controllers in an assembly /// </summary> /// <param name="apiModule">The apíModule instance.</param> /// <param name="assembly">The assembly to load WebApi Controllers from. Leave null to load from the currently executing assembly.</param> /// <returns>The webserver instance.</returns> public static WebApiModule LoadApiControllers(this WebApiModule apiModule, Assembly assembly = null) { if (apiModule == null) { throw new ArgumentException("Argument cannot be null.", "apiModule"); } var types = (assembly ?? Assembly.GetExecutingAssembly()).GetTypes(); var apiControllers = types.Where(x => x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof(WebApiController))).ToArray(); if (apiControllers.Any()) { foreach (var apiController in apiControllers) { apiModule.RegisterController(apiController); } } return(apiModule); }
private static WebServer CreateWebServer(string url) { // Opções do servidor var options = new WebServerOptions(); options.WithUrlPrefix(url); // Criação do servidor var server = new WebServer(options); server.WithCors(ConfigurationManager.AppSettings["origin"]); server.HandleUnhandledException(CustomExceptionHandler.ResponseForUnhandledException); server.HandleHttpException(CustomExceptionHandler.ResponseForHttpException); // Criação do módulo de API var module = new WebApiModule("/"); module.WithController <SatController>(); server.WithModule(module); return(server); }
protected override void AdaptModule(WebApiModule webApiModule) { webApiModule.RegisterController <ImplicitGrantAuthController>(); }
protected override void AdaptModule(WebApiModule webApiModule) { webApiModule.RegisterController <AuthorizationCodeAuthController>(); }
private static void Main(string[] args) { var shut_down_source = new CancellationTokenSource(); //var shutting_down = false; Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { e.Cancel = true; shut_down_source.Cancel(); }; #region Setup var arguments = new Arguments(args); var config_file_path = arguments["config-file"] ?? "config.json"; var config_arg_text = arguments["config"]; string config_file_text = null; if (!IsNullOrEmpty(config_file_path)) { if (!File.Exists(config_file_path)) { throw new FileNotFoundException("Config file does not exist at path", config_file_path); } config_file_text = File.ReadAllText(config_file_path); } JsonData config = new JsonData(); if (!IsNullOrEmpty(config_file_text)) { config = JsonMapper.ToObject(config_file_text); } if (!IsNullOrEmpty(config_arg_text)) { var arg_config = JsonMapper.ToObject <Dictionary <string, JsonData> >(config_arg_text); foreach (var key in arg_config.Keys) { config[key] = arg_config[key]; } } config.TryGetValue("WebSocket", out JsonData websocket_config); websocket_config.TryGetValue("Certificate", out JsonData websocket_cert_config); X509Certificate2 certificate = null; if (!TryArg(config, arguments, "FirstName", "first", out string first_name)) { throw new ArgumentException("First name must be specified"); } TryArg(config, arguments, "LastName", "last", out string last_name); TryArg(config, arguments, "Password", "pass", out string password); if (!TryArg(config, arguments, "LoginURI", "login-uri", out string login_uri)) { login_uri = Settings.AGNI_LOGIN_SERVER; } TryArg(config, arguments, "StartLocation", "start-location", out string start_location); bool ws_location_defined = TryArg(websocket_config, arguments, "Location", "ws", out string ws_location); bool ws_cert_path_defined = TryArg(websocket_cert_config, arguments, "Path", "ws-cert-path", out string ws_cert_path); if (!ws_location_defined) { if (ws_cert_path_defined) { ws_location = "wss://127.0.0.1:5756"; } else { ws_location = "ws://127.0.0.1:5756"; } } if (ws_cert_path_defined) { if (TryArg(websocket_cert_config, arguments, "Password", "ws-cert-pass", out string ws_cert_password)) { certificate = new X509Certificate2(ws_cert_path, ws_cert_password); } else { certificate = new X509Certificate2(ws_cert_path); } } TryArg(config, arguments, "StandaloneAddress", "standalone-address", out string standalone_binding_address); TryArg(config, arguments, "DummySession", "dummy-session", out bool dummy_session); #endregion Setup #region Server var server = new SLHWebSocketServer(ws_location) { Certificate = certificate }; server.Start(); #endregion Server #region Client SLHClient client = null; var logged_out = false; #endregion Client if (dummy_session) { #region Standalone if (!IsNullOrEmpty(standalone_binding_address)) { var standalone = WebServer .Create(standalone_binding_address) .WithStaticFolderAt("html"); standalone.RunAsync(shut_down_source.Token); } #endregion Standalone Logger.Log("Using dummy session mode without Second Life client.", Helpers.LogLevel.Warning); while (!shut_down_source.IsCancellationRequested) { Thread.Sleep(100); } } else { client = new SLHClient { Throttle = { Wind = 0, Cloud = 0, Land = 1000000, Task = 1000000, } }; #region Standalone if (!IsNullOrEmpty(standalone_binding_address)) { var standalone = WebServer .Create(standalone_binding_address) .WithStaticFolderAt("html"); // TODO: move APIs to a separate, non-standalone web server var web_api_module = new WebApiModule(); web_api_module.RegisterController((cx) => new TextureWebAPIController(cx, client)); standalone.RegisterModule(web_api_module); standalone.RunAsync(shut_down_source.Token); } #endregion Standalone var login_status = LoginStatus.None; string login_fail_reason = null; client.Network.LoginProgress += (sender, e) => { login_status = e.Status; login_fail_reason = e.FailReason; }; client.Network.LoggedOut += (sender, e) => { logged_out = true; }; // Legacy fix if (IsNullOrEmpty(last_name)) { last_name = "Resident"; } if (IsNullOrEmpty(password)) { Console.Write($"Password for {first_name} {last_name}: "); password = GetPassword(); } var login_params = client.Network.DefaultLoginParams(first_name, last_name, password, Product, Version); if (!IsNullOrEmpty(start_location)) { login_params.Start = start_location; } if (!IsNullOrEmpty(login_uri)) { login_params.URI = login_uri; } using (var slh = new SLH(client, server)) { client.Network.BeginLogin(login_params); while (login_status != LoginStatus.Success) { if (login_status == LoginStatus.Failed) { throw new LoginFailedException(login_fail_reason); } Thread.Sleep(200); } while (!logged_out) { if (shut_down_source.IsCancellationRequested) { client.Network?.Logout(); } Thread.Sleep(100); } } } }
public Server(Client client) : base(e => e .WithUrlPrefix($"{allSources}:{port}") .WithMode(HttpListenerMode.EmbedIO)) { this.client = client; config = client.config; // Grab types at runtime. var assembly = GetType().Assembly; if (assembly == null) { throw new Exception("Assembly missing, server cannot start."); } var types = assembly.GetTypes(); // Will be used to create controller generic factories for EmbedIO. var factoryMethod = typeof(Server).GetMethod(nameof(makeFactory), BindingFlags.Instance | BindingFlags.NonPublic); if (factoryMethod == null) { throw new Exception("Missing factory method, server cannot start."); } // authApi -> Routes that require authentication (AuthenticationModule). // openApi -> Any open routes (/login). var authApi = new WebApiModule("/"); var openApi = new WebApiModule("/"); foreach (var type in types) { // Look through to find a type that extends ServerController and has the Controller attribute. if (type == typeof(ServerController)) { continue; } if (!typeof(ServerController).IsAssignableFrom(type)) { continue; } var attributes = type.GetCustomAttributes(typeof(ControllerInfo), true); if (!attributes.Any()) { continue; } // authorization fields will be used to decide if endpoints will be protected by AuthorizationModule. var attribute = (ControllerInfo)attributes.First(); var api = attribute.authorization ? authApi : openApi; // Make the factory. var genericFactory = (Func <WebApiController>)factoryMethod .MakeGenericMethod(type) .Invoke(this, new object[] { }); if (genericFactory == null) { throw new Exception($"Cannot create factory for {type.Name}."); } // Add the controller. api.WithController(type, genericFactory); } // This breaks exception messages for the login endpoint but I can't care less. openApi.OnHttpException = (context, exception) => { // We want to ignore Not Found exceptions so routes will get passed down to AuthorizationModule. if (exception.StatusCode == 404) { return(Task.CompletedTask); } // Otherwise, do our best to make a friendly error message. context.SetHandled(); exception.PrepareResponse(context); if (exception.Message != null) { context.Response.OutputStream.Write( Encoding.UTF8.GetBytes(exception.Message)); } return(Task.CompletedTask); }; // Register our modules. this .WithModule(new ModuleGroup("/", false).WithModule(openApi)) .WithModule(new AuthorizationModule("/", this, authApi)) .WithLocalSessionManager(); }
protected abstract void AdaptModule(WebApiModule webApiModule);