当前位置: 首页>>代码示例>>C#>>正文


C# SelfHost.HttpSelfHostServer类代码示例

本文整理汇总了C#中System.Web.Http.SelfHost.HttpSelfHostServer的典型用法代码示例。如果您正苦于以下问题:C# HttpSelfHostServer类的具体用法?C# HttpSelfHostServer怎么用?C# HttpSelfHostServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpSelfHostServer类属于System.Web.Http.SelfHost命名空间,在下文中一共展示了HttpSelfHostServer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        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();
        }
开发者ID:randelramirez,项目名称:IntroductionWebApi,代码行数:31,代码来源:Program.cs

示例2: Main

    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();
        }
    }
开发者ID:nikoudel,项目名称:SmartHome,代码行数:25,代码来源:Program.cs

示例3: CreateHttpClient

        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;
            }
        }
开发者ID:JeffryGonzalez,项目名称:HRSolution,代码行数:25,代码来源:Helpers.cs

示例4: Main

        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();
            }
        }
开发者ID:Lords-Von-Handschreiber,项目名称:Juke-Mobile-Prototype,代码行数:29,代码来源:Program.cs

示例5: Main

        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();
        }
开发者ID:nywebman,项目名称:ASPNETWebApiSelfHost,代码行数:33,代码来源:Program.cs

示例6: Start

        public void Start()
        {
            selfHostServer = new HttpSelfHostServer(httpSelfHostConfiguration);
            selfHostServer.OpenAsync();

            Logger.Info("Started management app host");
        }
开发者ID:jonnii,项目名称:statr,代码行数:7,代码来源:ManagementBootstrapper.cs

示例7: Given_command_server_runnig

        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;
                }
            }
        }
开发者ID:JustApplications,项目名称:zaz,代码行数:31,代码来源:When_posting_command_to_server_that_fails.cs

示例8: OpenConfiguredServiceHost

 public static HttpSelfHostServer OpenConfiguredServiceHost(this CommandsController @this, string url)
 {
     var config = ZazServer.ConfigureAsSelfHosted(url);
     var host = new HttpSelfHostServer(config);
     host.OpenAsync().Wait();
     return host;
 }
开发者ID:JustApplications,项目名称:zaz,代码行数:7,代码来源:__Utils.cs

示例9: Main

        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();
        }
开发者ID:darrelmiller,项目名称:ApiRouter,代码行数:34,代码来源:Program.cs

示例10: SampleService

        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);
        }
开发者ID:RainBowChina,项目名称:IISLogAnalyzer,代码行数:35,代码来源:SampleService.cs

示例11: Body_WithSingletonControllerInstance_Fails

        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();
        }
开发者ID:douchedetector,项目名称:mvc-razor,代码行数:33,代码来源:CustomControllerFactoryTest.cs

示例12: Main

        /// <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();
                }
            }
        }
开发者ID:CryptidID,项目名称:Cryptid,代码行数:30,代码来源:Program.cs

示例13: WebApiTest

		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
				            };
		}
开发者ID:hibernating-rhinos,项目名称:RavenFS,代码行数:27,代码来源:WebApiTest.cs

示例14: Init

        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);
        }
开发者ID:ZooLab,项目名称:thinking-home,代码行数:25,代码来源:ListenerPlugin.cs

示例15: Main

        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();
            }
        }
开发者ID:grimcoder,项目名称:ProduceMarketRESTWebAPI,代码行数:27,代码来源:Program.cs


注:本文中的System.Web.Http.SelfHost.HttpSelfHostServer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。