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();
        }
Ejemplo n.º 2
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
				            };
		}
Ejemplo n.º 3
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();
                }
            }
        }
        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();
        }
Ejemplo n.º 5
0
        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();
        }
Ejemplo n.º 6
0
        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();
            }
        }
Ejemplo n.º 7
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();
         }
     }
 }
Ejemplo n.º 8
0
 public void Setup()
 {
     BaseAddress = GetBaseAddress();
     HttpConfiguration = GetHttpConfiguration();
     Server = new HttpSelfHostServer(HttpConfiguration);
     Server.OpenAsync().Wait();
 }
Ejemplo n.º 9
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();
                }
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            // Set up server configuration 
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost:8080");

            //Route Catches the GET PUT DELETE typical REST based interactions (add more if needed)
            config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional },
                new { httpMethod = new HttpMethodConstraint(HttpMethod.Get, HttpMethod.Put, HttpMethod.Delete) });

            //This allows POSTs to the RPC Style methods http://api/controller/action
            config.Routes.MapHttpRoute("API RPC Style", "api/{controller}/{action}",
                new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });

            //Finally this allows POST to typeical REST post address http://api/controller/
            config.Routes.MapHttpRoute("API Default 2", "api/{controller}/{action}",
                new { action = "Post" },
                new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
            
            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
Ejemplo n.º 11
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();
        }
Ejemplo n.º 12
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();
            }
        }
Ejemplo n.º 13
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();
            }

        }
Ejemplo n.º 14
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();
        }
    }
Ejemplo n.º 15
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();
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            //var config = new HttpSelfHostConfiguration("http://localhost:8999");
            var config = new MyConfig("http://localhost:8999");
            config.Routes.MapHttpRoute(
                "DefaultRoute", "{controller}/{id}",
                new { id = RouteParameter.Optional });
            //custom message processing
            //var server = new HttpSelfHostServer(config,
            //    new MyNewSimpleMessagehandler());

            //controller message processing
            var server = new HttpSelfHostServer(config,
                new MyNewSimpleMessagehandler());

            server.OpenAsync();

            //trick, calls server just created to  confirm it works
            var client = new HttpClient(server);
            client.GetAsync("http://localhost:8999/simple")
                .ContinueWith((t) =>
                    {
                        var result = t.Result;
                        result.Content.ReadAsStringAsync()
                            .ContinueWith((rt) => {
                                Console.WriteLine("Client got " + rt.Result);
                    });
                });
            //

            Console.WriteLine("opening web api selfhost ");
            Console.ReadKey();
        }
        public void Given_command_server_runnig()
        {
            var config = ZazServer.ConfigureAsSelfHosted(URL, new ServerConfiguration
            {
                Registry = new FooCommandRegistry(),
                Broker = new DelegatingCommandBroker((cmd, ctx) =>
                {
                    throw new InvalidOperationException("Server failed...");
                    // return Task.Factory.StartNew(() => { });
                })
            });

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

                // Client side
                var bus = new ZazClient(URL);
                try
                {
                    bus.PostAsync(new FooCommand
                    {
                        Message = "Hello world"
                    }).Wait();
                }
                catch (Exception ex)
                {
                    _resultEx = ex;
                }
            }
        }
        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();
            }
        }
Ejemplo n.º 19
0
        public void Start()
        {
            selfHostServer = new HttpSelfHostServer(httpSelfHostConfiguration);
            selfHostServer.OpenAsync();

            Logger.Info("Started management app host");
        }
Ejemplo n.º 20
0
        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();
            }
        }
Ejemplo n.º 21
0
        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;
        }
Ejemplo n.º 22
0
 public void Start()
 {
     using (var server = new HttpSelfHostServer(_httpSelfHostConfigurationWrapper.Create()))
     {
         server.OpenAsync().Wait();
     }
 }
Ejemplo n.º 23
0
        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();
            }
        }
Ejemplo n.º 24
0
        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;
        }
Ejemplo n.º 25
0
        public static void Main(string[] args)
        {


            HttpSelfHostServer server = null;
            try
            {
                var config = new HttpSelfHostConfiguration("http://localhost:3002/")
                {
                };
                //config.Formatters.Add(new HtmlMediaTypeFormatter());
                var todoList = new Application();
                config.Routes.Add("Noodles", config.Routes.CreateRoute("{*path}",
                    new HttpRouteValueDictionary("route"),
                    constraints: null,
                    dataTokens: null,
                    handler: new NoodlesHttpMessageHandler((r) => todoList)
                    ));
                server = new HttpSelfHostServer(config);

                server.OpenAsync().Wait();

                Console.WriteLine("Hit ENTER to exit");
                Console.ReadLine();
            }
            finally
            {
                if (server != null)
                {
                    server.CloseAsync().Wait();
                }
            }


        }
Ejemplo n.º 26
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();
            //}
        }
Ejemplo n.º 27
0
 public static HttpSelfHostServer OpenConfiguredServiceHost(this CommandsController @this, string url)
 {
     var config = ZazServer.ConfigureAsSelfHosted(url);
     var host = new HttpSelfHostServer(config);
     host.OpenAsync().Wait();
     return host;
 }
Ejemplo n.º 28
0
 public void Start()
 {
     Log.Info("Starting");
     Server = new HttpSelfHostServer(Config);
     Server.OpenAsync().Wait();
     Log.Info("Started");
 }
        public void Given_command_server_runnig()
        {
            var config = ZazServer.ConfigureAsSelfHosted(URL);

            _host = new HttpSelfHostServer(config);
            _host.OpenAsync().Wait();
        }
            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();
            }
        public void SetupHost()
        {
            baseAddress = String.Format("http://localhost:{0}/", HttpSelfHostServerTest.TestPort);

            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);

            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();
        }
Ejemplo n.º 32
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);
        }
        // HttpSelfHostServer has a small latency between CloseAsync.Wait
        // completing and other async tasks still running.  Theory driven
        // tests run quickly enough they sometimes attempt to open when the
        // prior test is still finishing those async tasks.
        private static void SafeOpen(HttpSelfHostServer server)
        {
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    server.OpenAsync().Wait();
                    return;
                }
                catch (Exception)
                {
                    if (i == 9)
                    {
                        System.Diagnostics.Debug.WriteLine("HttpSelfHostServerTests.SafeOpen failed to open server at " + server.Configuration.VirtualPathRoot);
                        throw;
                    }

                    Thread.Sleep(200);
                }
            }
        }
Ejemplo n.º 34
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();
                                    }
                                }
                }
            }
        }
Ejemplo n.º 35
-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();
            }
        }