• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# SelfHost.HttpSelfHostConfiguration类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: getHostConfiguration

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


示例17: Main

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


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


示例19: SendJsonGetCode

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


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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# SelfHost.HttpSelfHostServer类代码示例发布时间:2022-05-26
下一篇:
C# Routing.UrlHelper类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap