コード例 #1
0
ファイル: Program.cs プロジェクト: CryptidID/Cryptid
        /// <summary>
        /// The program main method
        /// </summary>
        /// <param name="args">The program arguments</param>
        private static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration(ServiceAddress);

            config.MapHttpAttributeRoutes();
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

            using (var server = new HttpSelfHostServer(config)) {
                try {
                    server.OpenAsync().Wait();
                    Console.WriteLine("Service running on " + ServiceAddress + ". Press enter to quit.");
                    Console.ReadLine();
                }
                catch (Exception e) {
                    if (!IsAdministrator()) {
                        Console.WriteLine("Please restart as admin.");
                        Debug.WriteLine("Restart Visual Studio as admin");
                    }
                    else {
                        Console.WriteLine("Server failed to start.");
                    }
                    Console.ReadLine();
                }
            }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: fabiohvp/DocumentSigner
        private static HttpSelfHostConfiguration GetSettings()
        {
            var localhostAddress = ConfigurationManager.AppSettings[SettingsHelper.KEY_LOCALHOST_ADDRESS];
            var serverConfiguration = new HttpSelfHostConfiguration(localhostAddress);

            serverConfiguration.Filters
                .Add(new ExceptionResponseFilterAttribute());

            serverConfiguration.Routes
                .MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{parameters}",
                    defaults: new
                    {
                        parameters = RouteParameter.Optional
                    }
                );

            var xmlFormatter = serverConfiguration.Formatters.OfType<XmlMediaTypeFormatter>().First();
            var jsonFormatter = serverConfiguration.Formatters.OfType<JsonMediaTypeFormatter>().First();
            var cors = new EnableCorsAttribute("*", "GET", "GET");

            serverConfiguration.EnableCors(cors);
            serverConfiguration.Formatters.Remove(xmlFormatter);
            jsonFormatter.SerializerSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            
            return serverConfiguration;
        }
コード例 #3
0
        protected override void OnStart(string[] args)
        {
            Uri baseAddress = new Uri("http://" + ConfigurationManager.AppSettings["server"] + GetPort());
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress)
            {
                HostNameComparisonMode = HostNameComparisonMode.Exact
            };

            string origins = ConfigurationManager.AppSettings["corsItems"];
            if (string.IsNullOrEmpty(origins))
            {
                origins = "*";
            }
            config.EnableCors(new EnableCorsAttribute(origins, "*", "*"));

            var formatters = GlobalConfiguration.Configuration.Formatters;
            formatters.Remove(formatters.XmlFormatter);

            WebApiConfig.Register(config);
            config.MapHttpAttributeRoutes();
            config.EnsureInitialized();

            _server = new HttpSelfHostServer(config);
            // Start listening
            _server.OpenAsync().Wait();
            System.Console.WriteLine("Listening on " + baseAddress);
        }
コード例 #4
0
        static void StartServer()
        {

            var config = new HttpSelfHostConfiguration(ServiceAddress);

            config.Routes.MapHttpRoute(
                "API Default", "{controller}/{action}/{id}",
                new
                {
                    id = RouteParameter.Optional,
                    controller = new WinampController()
                });

            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
            var server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();          
        }
コード例 #5
0
        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;
            try
            {
                // Set up server configuration
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);

                config.EnableCors();

                config.Routes.MapHttpRoute(
                    name: "MoveLeft",
                    routeTemplate: "api/{controller}/{action}"
                );

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );

                // Create server
                server = new HttpSelfHostServer(config);

                // Start listening
                server.OpenAsync().Wait();
                Console.WriteLine("Listening on " + _baseAddress);

                // Call the web API and display the result
                HttpClient client = new HttpClient();
                client.GetStringAsync(_address).ContinueWith(
                    getTask =>
                    {
                        if (getTask.IsCanceled)
                        {
                            Console.WriteLine("Request was canceled");
                        }
                        else if (getTask.IsFaulted)
                        {
                            Console.WriteLine("Request failed: {0}", getTask.Exception);
                        }
                        else
                        {
                            Console.WriteLine("Client received: {0}", getTask.Result);
                        }
                    });

                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
                Console.WriteLine("Hit ENTER to exit...");
                Console.ReadLine();
            }
            finally
            {
                if (server != null)
                {
                    // Stop listening
                    server.CloseAsync().Wait();
                }
            }
        }
コード例 #6
0
        private async Task StartHttp()
        {
            var baseAddress = new Uri($"http://localhost:{PortSetting}/");
            try
            {
                // Set up server configuration
                var config = new HttpSelfHostConfiguration(baseAddress);
                // config.Services.Replace(typeof(ITraceWriter), new SimpleTracer());

                //Add our way too simple Authentication 
                config.Filters.Add(new ZvsAuthenticatioFilter(this));

                // Web API routes
                config.MapHttpAttributeRoutes();

                var resolver = new WebApi2PluginDependencyResolver(this);
                config.DependencyResolver = resolver;

                config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

                //config.Routes.MapHttpRoute(
                //    name: "DefaultApi",
                //    routeTemplate: "api/{controller}/{id}",
                //    defaults: new { id = RouteParameter.Optional }
                //);

                var builder = new ODataConventionModelBuilder();
                
                var scheduledTaskType = builder.EntityType<ScheduledTask>();
                scheduledTaskType.Ignore(t => t.StartTime);
                scheduledTaskType.Property(t => t.StartTimeOffset).Name = "StartTime";

                var deviceValueHistoryTaskType = builder.EntityType<DeviceValueHistory>();
                deviceValueHistoryTaskType.Ignore(t => t.DateTime);
                deviceValueHistoryTaskType.Property(t => t.DateTimeOffset).Name = "DateTime";
                
                var logEntryType = builder.EntityType<LogEntry>();
                logEntryType.Ignore(t => t.Datetime);
                logEntryType.Property(t => t.DateTimeOffset).Name = "Datetime";

                builder.EntitySet<Command>("Commands");
                var cExecute = builder.EntityType<Command>().Action("Execute");
                cExecute.Parameter<string>("Argument");
                cExecute.Parameter<string>("Argument2");


                builder.EntitySet<BuiltinCommand>("BuiltinCommands");
                builder.EntitySet<Device>("Devices");
                builder.EntitySet<DeviceCommand>("DeviceCommands");
                builder.EntitySet<DeviceTypeCommand>("DeviceTypeCommands");
                builder.EntitySet<DeviceValueTrigger>("DeviceValueTriggers");
                builder.EntitySet<DeviceValue>("DeviceValues");
                builder.EntitySet<DeviceValueHistory>("DeviceValueHistories");
                builder.EntitySet<Group>("Groups");
                builder.EntitySet<Scene>("Scenes");
                builder.EntitySet<SceneStoredCommand>("SceneStoredCommands");
                builder.EntitySet<ScheduledTask>("ScheduledTasks");
                builder.EntitySet<LogEntry>("LogEntries");
                builder.Namespace = "Actions";
                config.MapODataServiceRoute("ODataRoute", "odata4", builder.GetEdmModel());

                //config.MapODataServiceRoute(
                //routeName: "ODataRoute",
                //routePrefix: null,
                //model: builder.GetEdmModel());

                // Create server
                HttpSelfHostServer = new HttpSelfHostServer(config);

                // Start listening
                await HttpSelfHostServer.OpenAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
            }

            await Log.ReportInfoFormatAsync(CancellationToken, "WebApi2 Server Online on port {0} {1} SSL", baseAddress, UseSslSetting ? "using" : "not using");
        }
コード例 #7
0
        static HttpSelfHostServer ConfigureServer(string serverUrl)
        {
            // set up the server side
            var config = new HttpSelfHostConfiguration(serverUrl);
            // Attribute routing
            config.MapHttpAttributeRoutes();

            // Convention-based routing
            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            // set the default WebAPI format to JSON
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            // enable Cross Origin Resource Sharing
            config.EnableCors();

            return new HttpSelfHostServer(config);
        }
コード例 #8
-1
        public static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://127.0.0.1:3001");

            config.MapHttpAttributeRoutes();
            config.EnableCors();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "ReportsApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }