public void SetUp()
        {
            var config = new HttpSelfHostConfiguration(URL);

            ZazServer.Configure(config, Prefix1, new ServerConfiguration
            {
                Registry = new FooCommandRegistry(),
                Broker = new DelegatingCommandBroker((o, context) =>
                {
                    _api1Command = (FooCommand)o;
                    return Task.Factory.StartNew(() => { });
                }),
            });
            ZazServer.Configure(config, Prefix2, new ServerConfiguration
            {
                Registry = new FooCommandRegistry(),
                Broker = new DelegatingCommandBroker((o, context) =>
                {
                    _api2Command = (FooCommand)o;
                    return Task.Factory.StartNew(() => { });
                }),
            });

            _host = new HttpSelfHostServer(config);
            _host.OpenAsync().Wait();
        }
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8999");
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            // using asp.net like hosting
            // HttpSelfHostServer is using a different constructor compared to the previous project (SelfHost1)
            var server = new HttpSelfHostServer(config);
            var task = server.OpenAsync();
            task.Wait();
            Console.WriteLine("Server is up and running");
            Console.WriteLine("Hit enter to call server with client");
            Console.ReadLine();

            // HttpSelfHostServer, derives from HttpMessageHandler => multiple level of inheritance
            var client = new HttpClient(server);
            client.GetAsync("http://localhost:8999/api/my").ContinueWith(t =>
            {
                var result = t.Result;
                result.Content.ReadAsStringAsync()
                    .ContinueWith(rt =>
                    {
                        Console.WriteLine("client got response" + rt.Result);
                    });
            });

            Console.ReadLine();
        }
Example #3
0
 static void Main(string[] args)
 {
     HttpSelfHostServer server = null;
     try {
         // Set up server configuration
         HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(BaseAddress);
         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);
         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();
         }
     }
 }
        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);
        }
        private static void Main(string[] args) {
            string prefix = "http://localhost:8080";
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(prefix);
            config.Routes.MapHttpRoute("Default", "{controller}/{action}");

            // Append our custom valueprovider to the list of value providers.
            config.Services.Add(typeof (ValueProviderFactory), new HeaderValueProviderFactory());

            HttpSelfHostServer server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();

            try {
                // HttpClient will make the call, but won't set the headers for you. 
                HttpClient client = new HttpClient();
                var response = client.GetAsync(prefix + "/ValueProviderTest/GetStuff?id=20").Result;

                // Browsers will set the headers. 
                // Loop. You can hit the request via: http://localhost:8080/Test2/GetStuff?id=40
                while (true) {
                    Thread.Sleep(1000);
                    Console.Write(".");
                }
            }
            finally {
                server.CloseAsync().Wait();
            }
        }
Example #6
0
 private HttpSelfHostConfiguration GetHttpConfiguration()
 {
     var config = new HttpSelfHostConfiguration(BaseAddress);
     config.Routes.MapHttpRoute("Locator", "api.xml", new {controller = "ApiXml"});
     config.Routes.MapHttpRoute("Api", "api.asp", new {controller = "ApiAsp"});
     return config;
 }
Example #7
0
        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;
            try
            {
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);
                config.HostNameComparisonMode = HostNameComparisonMode.Exact;

                // Register default route
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}"
                );

                server = new HttpSelfHostServer(config);
                server.OpenAsync().Wait();
                Console.WriteLine("Listening on " + baseAddress);
                Console.WriteLine("Hit ENTER to exit...");
                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)
                {
                    server.CloseAsync().Wait();
                }
            }
        }
Example #8
0
		public WebApiTest()
		{
			IOExtensions.DeleteDirectory("Test");
			NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(19079);
			Task.Factory.StartNew(() => // initialize in MTA thread
				                      {
					                      config = new HttpSelfHostConfiguration(Url)
						                               {
							                               MaxReceivedMessageSize = Int64.MaxValue,
							                               TransferMode = TransferMode.Streamed
						                               };
					                      var configuration = new InMemoryConfiguration();
					                      configuration.Initialize();
					                      configuration.DataDirectory = "~/Test";
					                      ravenFileSystem = new RavenFileSystem(configuration);
					                      ravenFileSystem.Start(config);
				                      })
			    .Wait();

			server = new HttpSelfHostServer(config);
			server.OpenAsync().Wait();

			WebClient = new WebClient
				            {
					            BaseAddress = Url
				            };
		}
Example #9
0
        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;
        }
Example #10
0
        static void Main(string[] args)
        {
            var address = "http://localhost:900";
            var config = new HttpSelfHostConfiguration(address);
            config.MapHttpAttributeRoutes();

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Server running at {0}. Press any key to exit", address);

                var client = new HttpClient() {BaseAddress = new Uri(address)};

                var persons = client.GetAsync("person").Result;
                Console.WriteLine(persons.Content.ReadAsStringAsync().Result);

                var newPerson = new Person {Id = 3, Name = "Luiz"};
                var response = client.PostAsJsonAsync("person", newPerson).Result;

                if (response.IsSuccessStatusCode)
                {
                    var person3 = client.GetAsync("person/3").Result;
                    Console.WriteLine(person3.Content.ReadAsStringAsync().Result);
                }

                Console.ReadLine();
            }

        }
        public static HttpStatusCode SendJsonGetCode(string routeTemp, string uri, string json)
        {
            HttpStatusCode actualHttpCode;

            HttpSelfHostConfiguration config
                = new HttpSelfHostConfiguration("http://localhost/");
            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: routeTemp
                );

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            using (HttpClient client = getJsonClient())
            {
                server.OpenAsync().Wait();
                using (HttpRequestMessage request =
                    getJsonRequest(HttpMethod.Post, uri, json))
                using (HttpResponseMessage response = client.SendAsync(request).Result)
                {
                    actualHttpCode = response.StatusCode;
                }
                server.CloseAsync().Wait();
            }
            return actualHttpCode;
        }
		public HttpSelfHostServer Build()
		{
			var log = HostLogger.Get(typeof(WebApiConfigurator));

			var baseAddress = new UriBuilder(Scheme, Domain, Port).Uri;

			log.Debug(string.Format("[Topshelf.WebApi] Configuring WebAPI Selfhost for URI: {0}", baseAddress));

			var config = new HttpSelfHostConfiguration(baseAddress);

			if(DependencyResolver != null)
				config.DependencyResolver = DependencyResolver;

			if (ServerConfigurer != null)
			{
				ServerConfigurer(config);
			}

			if (RouteConfigurer != null)
			{
				RouteConfigurer(config.Routes);
			}

			Server = new HttpSelfHostServer(config);

			log.Info(string.Format("[Topshelf.WebApi] WebAPI Selfhost server configurated and listening on: {0}", baseAddress));

			return Server;
		}
Example #13
0
    static void Main(string[] args)
    {
        // run as administrator: netsh http add urlacl url=http://+:56473/ user=machine\username
        // http://www.asp.net/web-api/overview/older-versions/self-host-a-web-api

        var config = new HttpSelfHostConfiguration("http://localhost:56473");

        config.Routes.MapHttpRoute("Default", "{controller}.json");

        config.Formatters.Remove(config.Formatters.XmlFormatter);

        config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
            new Newtonsoft.Json.Converters.StringEnumConverter());

        config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
            new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm" });

        using (HttpSelfHostServer server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();

            Console.WriteLine("Press Enter to quit...");
            Console.ReadLine();
        }
    }
Example #14
0
        static void Main(string[] args)
        {
            Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var selfConfig = cfg.GetSection("SeifConfiguration") as SeifConfiguration;

            //var servConfig = new ProviderConfiguration();
            //servConfig.ApiDomain = "api.aaa.com";
            //servConfig.ApiIpAddress = "172.16.1.121";
            //servConfig.SerializeMode = "ssjson";
            //servConfig.Protocol = "Http";
            //servConfig.AddtionalFields.Add(AttrKeys.ApiGetEntrance, "api/get");
            //servConfig.AddtionalFields.Add(AttrKeys.ApiPostEntrance, "api/post");

            //var clientConfig = new ConsumerConfiguration();

            //var registryProvider = new RedisRegistryProvider();
            //var registry = new GenericRegistry(registryProvider, registryProvider);
            //var typeBuilder = new AutofacTypeBuilder();
            ////SeifApplication.Initialize(registry, servConfig, clientConfig, typeBuilder, new ISerializer[]{new ServiceStackJsonSerializer()});

            SeifApplication.Initialize(selfConfig);
            SeifApplication.ExposeService<IDemoService, DemoService>();
            //SeifApplication.ReferenceService<IEchoService>(new ProxyOptions(), new IInvokeFilter[0]);

            SeifApplication.AppEnv.TypeBuilder.Build();

            var config = new HttpSelfHostConfiguration("http://localhost:3333");
            config.Filters.Add(new ExceptionFilter());
            config.Routes.MapHttpRoute("default", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
            var server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();
            Console.WriteLine("Server is opened");
            Console.Read();
        }
Example #15
0
        static void Main(string[] args)
        {
            Assembly.Load("WebApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
            HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://localhost/selfhost/tyz");//指定基地址
            try
            {
                using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration))
                {
                    httpServer.Configuration.Routes.MapHttpRoute(
                     name: "DefaultApi",
                     routeTemplate: "api/{controller}/{id}",
                     defaults: new { id = RouteParameter.Optional });

                    httpServer.OpenAsync().Wait();
                    Console.Read();
                }
            }
            catch (Exception e)
            {
            }

            ////web API的SelfHost寄宿方式通过HttpSelfHostServer来完成
            //using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration))
            //{
            //    httpServer.Configuration.Routes.MapHttpRoute(
            //     name: "DefaultApi",
            //     routeTemplate: "api/{controller}/{id}",
            //     defaults: new { id = RouteParameter.Optional });

            //    httpServer.OpenAsync();//开启后,服务器开始监听来自网络的调用请求
            //    Console.Read();
            //}
        }
        public PrinterService()
        {
            InitializeComponent();

            config = new HttpSelfHostConfiguration(AppConfig.BaseUrl);
            config.MapHttpAttributeRoutes();
        }
        public SampleService(bool throwOnStart, bool throwOnStop, bool throwUnhandled, Uri address)
        {
            _throwOnStart = throwOnStart;
            _throwOnStop = throwOnStop;
            _throwUnhandled = throwUnhandled;
            if (!EventLog.SourceExists(EventSource))
            {
                EventLog.CreateEventSource(EventSource, "Application");
            }
            EventLog.WriteEntry(EventSource,
                String.Format("Creating server at {0}",
                address.ToString()));
            _config = new HttpSelfHostConfiguration(address);
            _config.Routes.MapHttpRoute("DefaultApi",
                "api/{controller}/{id}",
                new { id = RouteParameter.Optional }
            );
            _config.Routes.MapHttpRoute(
              "Default", "{controller}/{action}",
               new { controller = "Home", action = "Index", date = RouteParameter.Optional});
            const string viewPathTemplate = "SampleTopshelfService.Views.{0}";
            var templateConfig = new TemplateServiceConfiguration();
            templateConfig.Resolver = new DelegateTemplateResolver(name =>
            {
                string resourcePath = string.Format(viewPathTemplate, name);
                var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath);
                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            });
            Razor.SetTemplateService(new TemplateService(templateConfig));

            _server = new HttpSelfHostServer(_config);
        }
Example #18
0
        public static HttpClient CreateHttpClient()
        {
            var baseAddress = new Uri("http://localhost:8080");

            var config = new HttpSelfHostConfiguration(baseAddress);

            // ?
            Setup.Configure(config);

            var server = new HttpSelfHostServer(config);

            var client = new HttpClient(server); // <--- MAGIC!

            try
            {
                client.BaseAddress = baseAddress;
                return client;

            }
            catch
            {
                client.Dispose();
                throw;
            }
        }
Example #19
0
        static void Main(string[] args)
        {
            var baseurl = new Uri("http://localhost:9000/");
            var config = new HttpSelfHostConfiguration(baseurl);

            //config.MessageHandlers.Add(new GitHubApiRouter(baseurl));

            //config.Routes.Add("default", new TreeRoute("",new TreeRoute("home").To<HomeController>(),
            //                                              new TreeRoute("contact",
            //                                                        new TreeRoute("{id}",
            //                                                            new TreeRoute("address",
            //                                                                 new TreeRoute("{addressid}").To<ContactAddressController>())
            //                                                        ).To<ContactController>())
            //                                              )
            //                  );

            var route = new TreeRoute("api");
            route.AddWithPath("home", r => r.To<HomeController>());
            route.AddWithPath("contact/{id}",r => r.To<ContactController>());
            route.AddWithPath("contact/{id}/adddress/{addressid}", r => r.To<ContactAddressController>());
            route.AddWithPath("act/A", r => r.To<ActionController>().ToAction("A"));
            route.AddWithPath("act/B", r => r.To<ActionController>().ToAction("B"));

            config.Routes.Add("default", route);

            var host = new HttpSelfHostServer(config);
            host.OpenAsync().Wait();

            Console.WriteLine("Host open.  Hit enter to exit...");

            Console.Read();

            host.CloseAsync().Wait();
        }
        public void Body_WithSingletonControllerInstance_Fails()
        {
            // Arrange
            HttpClient httpClient = new HttpClient();
            string baseAddress = "http://localhost";
            string requestUri = baseAddress + "/Test";
            HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration(baseAddress);
            configuration.Routes.MapHttpRoute("Default", "{controller}", new { controller = "Test" });
            configuration.ServiceResolver.SetService(typeof(IHttpControllerFactory), new MySingletonControllerFactory());
            HttpSelfHostServer host = new HttpSelfHostServer(configuration);
            host.OpenAsync().Wait();
            HttpResponseMessage response = null;

            try
            {
                // Act
                response = httpClient.GetAsync(requestUri).Result;
                response = httpClient.GetAsync(requestUri).Result;
                response = httpClient.GetAsync(requestUri).Result;

                // Assert
                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
            }

            host.CloseAsync().Wait();
        }
Example #21
0
        private static HttpSelfHostConfiguration getHostConfiguration(string serverUri, bool allowRemoteConnections)
        {
            var config = new HttpSelfHostConfiguration(serverUri)
            {
                // to avoid `(413) Request Entity Too Large` exceptions
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue
            };

            if (!allowRemoteConnections)
            {
                // Only clients from the local machine will be able to invoke the hosted REST API.
                // It does NOT require admin privileges or a URL reservation.
                config.HostNameComparisonMode = HostNameComparisonMode.Exact;
            }

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

            var jsonSettings = new JsonSerializerSettings();
            jsonSettings.Converters.Add(new StringEnumConverter());
            config.Formatters.JsonFormatter.SerializerSettings = jsonSettings;
            return config;
        }
        static void Main(string[] args)
        {
            const string address = "http://localhost:8080";

            var config = new HttpSelfHostConfiguration(address);

            config.Formatters.Insert(0, new AssetFormatter());

            config.Routes.MapHttpRoute(
                "Admin Web", "admin", new { controller = "Admin" }
                );

            config.Routes.MapHttpRoute(
                "Assets", "assets/{type}/{asset}", new { controller = "Assets" }
                );

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

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Started host on " + address + "/admin/");
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
        static void Main(string[] args)
        {
            var cfg = new HttpSelfHostConfiguration("http://localhost:1337");

            cfg.MaxReceivedMessageSize = 16L * 1024 * 1024 * 1024;
            cfg.TransferMode = TransferMode.StreamedRequest;
            cfg.ReceiveTimeout = TimeSpan.FromMinutes(20);

            cfg.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            cfg.Routes.MapHttpRoute(
                "Default", "{*res}",
                new { controller = "StaticFile", res = RouteParameter.Optional });

            var db = new EmbeddableDocumentStore { DataDirectory = new FileInfo("db/").DirectoryName };
            db.Initialize();
            cfg.Filters.Add(new RavenDbApiAttribute(db));

            using (HttpSelfHostServer server = new HttpSelfHostServer(cfg))
            {
                Console.WriteLine("Initializing server.");
                server.OpenAsync().Wait();
                Console.WriteLine("Server ready at: " + cfg.BaseAddress);
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
        public static JObject SendJsonGetJson(HttpMethod method, string routeTemp, string uri, string json)
        {
            JObject result;

            HttpSelfHostConfiguration config
                = new HttpSelfHostConfiguration("http://localhost/");
            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: routeTemp
                );

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            using (HttpClient client = getJsonClient())
            {
                server.OpenAsync().Wait();
                using (HttpRequestMessage request =
                    getJsonRequest(method, uri, json))
                using (HttpResponseMessage response = client.SendAsync(request).Result)
                {
                    string responseJson = response.Content.ReadAsStringAsync().Result;
                    result = JObject.Parse(responseJson);
                }
                server.CloseAsync().Wait();
            }
            return result;
        }
        static void Main(string[] args)
        {
            // classic
            var config = new HttpSelfHostConfiguration("http://localhost:18081");

            // HTTPS
            //var config = new HttpsSelfHostConfiguration("http://localhost:18081");

            // NTLM
            //var config = new NtlmHttpSelfHostConfiguration("http://localhost:18081");


            // BASIC AUTHENTICATION
            //var config = new BasicAuthenticationSelfHostConfiguration("http://localhost:18081",
            //    (un, pwd) => un == "johndoe" && pwd == "123456");



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

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
 private static void Configure(HttpSelfHostConfiguration config)
 {
     config.Routes.MapHttpRoute("Default Route", "api/{controller}", new { controller = "Home" });
     config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
     config.Filters.Add(new ServiceControlErrorFilter());
     config.Filters.Add(new VersionInformationFilter());
 }
Example #27
0
        public override void Init()
        {
            var actions = new HttpMethodCollection();
            foreach (var action in RequestReceived)
            {
                actions.RegisterMethod(action.Metadata, action.Value);
            }

            var config = new HttpSelfHostConfiguration(BASE_URL_HTTP)
            {
                DependencyResolver = new DependencyResolver(actions, Logger)
            };

            config.Routes.MapHttpRoute(
                "API Default", "api/{pluginName}/{methodName}/{callback}",
                new
                {
                    controller = "Common",
                    action = "Get",
                    callback = RouteParameter.Optional
                })
                .DataTokens["Namespaces"] = new[] {"ThinkingHome.Plugins.Listener.Api"};

            server = new HttpSelfHostServer(config);
        }
Example #28
0
        /// <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();
                }
            }
        }
Example #29
0
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            // Attribute Routing
            config.Routes.MapHttpAttributeRoutes(cfg =>
            {
                cfg.ScanAssemblyOf<ProductsController>();

                // Must have this on, otherwise you need to specify RouteName in your attributes
                cfg.AutoGenerateRouteNames = true;
            });

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();

                Console.WriteLine("Routes:");

                config.Routes.Cast<HttpRoute>().LogTo(Console.Out);

                Console.WriteLine("Routes:");
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
Example #30
0
        public void HttpSelfHostConfiguration_CorrectClientCredentialType_WithX509CertificateValidator_Works(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)
        {
            // Arrange
            GC.KeepAlive(mode); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                X509CertificateValidator = new Mock <X509CertificateValidator>().Object
            };

            config.ClientCredentialType = clientCredentialType;

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);
        }
Example #31
0
        public void HttpSelfHostConfiguration_CorrectClientCredentialType_WithUsernamePasswordValidator_Works(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)
        {
            // Arrange
            GC.KeepAlive(mode); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                UserNamePasswordValidator = new CustomUsernamePasswordValidator()
            };

            config.ClientCredentialType = clientCredentialType;

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);
        }
Example #32
0
        public void HttpSelfHostConfiguration_ClientCredentialType_PropagatesToHttpBinding(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                ClientCredentialType = clientCredentialType
            };

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);

            Assert.Equal(clientCredentialType, binding.Security.Transport.ClientCredentialType);
            Assert.Equal(mode, binding.Security.Mode);
        }
Example #33
0
        public void HttpSelfHostConfiguration_MaxBufferSize_DoesNotTrackMaxReceivedMessageSizeWhenSet(
            long maxReceivedMessageSize,
            int maxBufferSize
            )
        {
            // Arrange
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost");

            config.MaxBufferSize          = maxBufferSize;
            config.MaxReceivedMessageSize = maxReceivedMessageSize;

            // Act & Assert
            Assert.Equal(maxBufferSize, config.MaxBufferSize);
            Assert.Equal(maxReceivedMessageSize, config.MaxReceivedMessageSize);
        }
Example #34
0
        public void SetupHost()
        {
            baseAddress = String.Format("http://localhost:{0}/", HttpSelfHostServerTest.TestPort);

            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);

            config.Routes.MapHttpRoute("Default", "{controller}/{action}", new { controller = "NullResponse" });

            messageHandler = new NullResponseMessageHandler();
            config.MessageHandlers.Add(messageHandler);

            server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();

            httpClient = new HttpClient();
        }
Example #35
0
        public void HttpSelfHostConfiguration_WrongClientCredentialType_WithUsernamePasswordValidator_Throws(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                UserNamePasswordValidator = new CustomUsernamePasswordValidator()
            };

            config.ClientCredentialType = clientCredentialType;

            Assert.Throws <InvalidOperationException>(() =>
            {
                // Act
                BindingParameterCollection parameters = config.ConfigureBinding(binding);
            });
        }
Example #36
0
        public void HttpSelfHostConfiguration_WrongClientCredentialType_WithX509CertificateValidator_Throws(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                X509CertificateValidator = new Mock <X509CertificateValidator>().Object
            };

            config.ClientCredentialType = clientCredentialType;

            Assert.Throws <InvalidOperationException>(() =>
            {
                // Act
                BindingParameterCollection parameters = config.ConfigureBinding(binding);
            });
        }
Example #37
0
            public SelfHostTester()
            {
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_testPort.BaseUri);

                BaseAddress = _testPort.BaseUri;

                config.HostNameComparisonMode = HostNameComparisonMode.Exact;
                config.Routes.MapHttpRoute("Default", "{controller}/{action}", new { controller = "NullResponse" });

                MessageHandler = new NullResponseMessageHandler();
                config.MessageHandlers.Add(MessageHandler);

                _server = new HttpSelfHostServer(config);
                _server.OpenAsync().Wait();

                HttpClient = new HttpClient();
            }
Example #38
0
        private void SetupHost()
        {
            baseAddress = String.Format("http://localhost/");

            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);

            config.HostNameComparisonMode = HostNameComparisonMode.Exact;
            config.Routes.MapHttpRoute(
                "Default",
                "{controller}/{action}",
                new { controller = "DeepNestedType" }
                );

            server = new HttpSelfHostServer(config);

            httpClient = new HttpClient(server);
        }
Example #39
0
        public void HttpSelfHostConfiguration_ClientCredentialType_RoundTrips()
        {
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost");

            Assert.Reflection.EnumPropertyWithoutIllegalValueCheck <HttpSelfHostConfiguration, HttpClientCredentialType>(
                config,
                c => c.ClientCredentialType,
                expectedDefaultValue: HttpClientCredentialType.None,
                roundTripTestValue: HttpClientCredentialType.Windows);

            // now let us check the illegal value differently
            config.ClientCredentialType = (HttpClientCredentialType)999;
            Assert.ThrowsArgumentOutOfRange(
                () =>
            {
                new HttpSelfHostServer(config).OpenAsync().Wait();
            }, "value", null, false, 999);
        }
Example #40
0
        public void HttpSelfHostConfiguration_NegativeTimeouts_ThrowArgumentOutOfRange()
        {
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost");
            TimeSpan negativeTimeout         = new TimeSpan(-1, 0, 0);

            Assert.ThrowsArgumentGreaterThanOrEqualTo(
                () => config.ReceiveTimeout = negativeTimeout,
                "value",
                "00:00:00",
                "-01:00:00"
                );
            Assert.ThrowsArgumentGreaterThanOrEqualTo(
                () => config.SendTimeout = negativeTimeout,
                "value",
                "00:00:00",
                "-01:00:00"
                );
        }
Example #41
0
        private static async Task <HttpSelfHostServer> CreateServerAsync(PortReserver port, TransferMode transferMode, bool ignoreRoute = false)
        {
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(BaseUri(port, transferMode));

            config.HostNameComparisonMode = HostNameComparisonMode.Exact;
            if (ignoreRoute)
            {
                config.Routes.IgnoreRoute("Ignore", "{controller}/{action}");
                config.Routes.IgnoreRoute("IgnoreWithConstraints", "constraint/values/{id}", constraints: new { constraint = new CustomConstraint() });
            }
            config.Routes.MapHttpRoute("Default", "{controller}/{action}");
            config.Routes.MapHttpRoute("Other", "other/{controller}/{action}");
            config.TransferMode = transferMode;
            config.MapHttpAttributeRoutes();

            HttpSelfHostServer server = new HttpSelfHostServer(config);
            await server.OpenAsync();

            return(server);
        }
        public void HttpSelfHostConfiguration_UseWindowsAuth_PropagatesToHttpBinding(string address, HttpBindingSecurityMode mode)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                UseWindowsAuthentication = true
            };

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);

            // Assert
            Assert.NotNull(parameters);
            ServiceCredentials serviceCredentials = parameters.Find <ServiceCredentials>();

            Assert.NotNull(serviceCredentials);
            Assert.Equal(HttpClientCredentialType.Windows, binding.Security.Transport.ClientCredentialType);
            Assert.Equal(mode, binding.Security.Mode);
        }
        private void SetupHosts()
        {
            try
            {
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(BaseUri(TransferMode.Buffered));
                config.Routes.MapHttpRoute("Default", "{controller}/{action}");
                _bufferServer = new HttpSelfHostServer(config);
                SafeOpen(_bufferServer);

                config = new HttpSelfHostConfiguration(BaseUri(TransferMode.Streamed));
                config.Routes.MapHttpRoute("Default", "{controller}/{action}");
                config.TransferMode = TransferMode.Streamed;
                _streamServer       = new HttpSelfHostServer(config);
                SafeOpen(_streamServer);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("HttpSelfHostServerTests.SetupHosts failed: " + ex.GetBaseException());
                throw;
            }
        }
        public void HttpSelfHostConfiguration_Settings_PropagateToBinding()
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost")
            {
                MaxBufferSize          = 10,
                MaxReceivedMessageSize = 11,
                TransferMode           = TransferMode.StreamedResponse,
                HostNameComparisonMode = HostNameComparisonMode.WeakWildcard
            };

            // Act
            config.ConfigureBinding(binding);

            // Assert
            Assert.Equal(10, binding.MaxBufferSize);
            Assert.Equal(11, binding.MaxReceivedMessageSize);
            Assert.Equal(TransferMode.StreamedResponse, binding.TransferMode);
            Assert.Equal(HostNameComparisonMode.WeakWildcard, binding.HostNameComparisonMode);
        }
        public void HttpSelfHostConfiguration_UserNamePasswordValidator_PropagatesToBinding(string address, HttpBindingSecurityMode mode)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            UserNamePasswordValidator validator = new Mock <UserNamePasswordValidator>().Object;
            HttpSelfHostConfiguration config    = new HttpSelfHostConfiguration(address)
            {
                UserNamePasswordValidator = validator
            };

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);

            // Assert
            Assert.NotNull(parameters);
            ServiceCredentials serviceCredentials = parameters.Find <ServiceCredentials>();

            Assert.NotNull(serviceCredentials);
            Assert.Equal(HttpClientCredentialType.Basic, binding.Security.Transport.ClientCredentialType);
            Assert.Equal(mode, binding.Security.Mode);
        }
Example #46
0
        public async Task SendAsync_ServiceModel_AddsSelfHostHttpRequestContext()
        {
            // Arrange
            using (PortReserver port = new PortReserver())
            {
                string baseUri = port.BaseUri;

                HttpRequestContext context = null;
                Uri via = null;

                Func <HttpRequestMessage, CancellationToken, Task <HttpResponseMessage> > sendAsync = (
                    r,
                    c
                    ) =>
                {
                    if (r != null)
                    {
                        context = r.GetRequestContext();
                    }

                    SelfHostHttpRequestContext typedContext = context as SelfHostHttpRequestContext;

                    if (typedContext != null)
                    {
                        via = typedContext.RequestContext.RequestMessage.Properties.Via;
                    }

                    return(Task.FromResult(new HttpResponseMessage()));
                };

                using (
                    HttpSelfHostConfiguration expectedConfiguration = new HttpSelfHostConfiguration(
                        baseUri
                        )
                    )
                {
                    expectedConfiguration.HostNameComparisonMode = HostNameComparisonMode.Exact;

                    using (HttpMessageHandler dispatcher = new LambdaHttpMessageHandler(sendAsync))
                        using (
                            HttpSelfHostServer server = new HttpSelfHostServer(
                                expectedConfiguration,
                                dispatcher
                                )
                            )
                            using (HttpClient client = new HttpClient())
                                using (
                                    HttpRequestMessage expectedRequest = new HttpRequestMessage(
                                        HttpMethod.Get,
                                        baseUri
                                        )
                                    )
                                {
                                    await server.OpenAsync();

                                    // Act
                                    using (HttpResponseMessage ignore = await client.SendAsync(expectedRequest))
                                    {
                                        // Assert
                                        SelfHostHttpRequestContext typedContext =
                                            (SelfHostHttpRequestContext)context;
                                        Assert.Equal(expectedRequest.RequestUri, via);
                                        Assert.Same(expectedConfiguration, context.Configuration);
                                        Assert.Equal(
                                            expectedRequest.RequestUri,
                                            typedContext.Request.RequestUri
                                            );

                                        await server.CloseAsync();
                                    }
                                }
                }
            }
        }
        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();
            }
        }