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


C# SelfHost.HttpSelfHostConfiguration类代码示例

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


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

示例1: GetHttpConfiguration

 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;
 }
开发者ID:pstephens,项目名称:fbclient,代码行数:7,代码来源:SetupFixture.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: Configure

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

示例5: 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

示例6: Main

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

示例7: SendJsonGetJson

        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;
        }
开发者ID:pacholik,项目名称:driving_scools_server,代码行数:26,代码来源:AssertHelper.cs

示例8: 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

示例9: 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

示例10: SetUp

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

示例11: 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

示例12: OnStart

        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);
        }
开发者ID:blueghostuk,项目名称:trainnotifier-server,代码行数:27,代码来源:Service.cs

示例13: Main

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

示例14: Main

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

示例15: GetSettings

        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;
        }
开发者ID:fabiohvp,项目名称:DocumentSigner,代码行数:28,代码来源:Program.cs


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