當前位置: 首頁>>代碼示例>>C#>>正文


C# Hosting.WebHostBuilder類代碼示例

本文整理匯總了C#中Microsoft.AspNetCore.Hosting.WebHostBuilder的典型用法代碼示例。如果您正苦於以下問題:C# WebHostBuilder類的具體用法?C# WebHostBuilder怎麽用?C# WebHostBuilder使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


WebHostBuilder類屬於Microsoft.AspNetCore.Hosting命名空間,在下文中一共展示了WebHostBuilder類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Main

        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseUrls("http://localhost:8080")
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            var restartTime = 0;

            Restart:

            try
            {
                host.Run();
            }
            catch (Exception ex)
            {
                Logger.Error("Unhandled exception occured while host is running.", ex);
                if (restartTime <= MaxRestartTime)
                {
                    restartTime++;

                    Logger.Info("Trying to restart...");

                    goto Restart;
                }
            }

            ClearUp();
        }
開發者ID:yhvicey,項目名稱:ConfigSync,代碼行數:33,代碼來源:Program.cs

示例2: Main

        public static void Main(string[] args)
        {
            while (true)
            {
                var host = new WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .Build();

                var lifetime = (IApplicationLifetime)host.Services.GetService(typeof(IApplicationLifetime));
                Task.Run(() =>
                {

                    while (true)
                    {
                        var line = Console.ReadLine();
                        if (line == "r")
                        {
                            Console.WriteLine("Restarting");
                            lifetime.StopApplication();
                            break;
                        }
                    }
                });

                host.Run();
            }
        }
開發者ID:pakrym,項目名稱:signoffs,代碼行數:30,代碼來源:Program.cs

示例3: Main

        public static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("KestrelHelloWorld <url to host>");
                return 1;
            }

            var url = new Uri(args[0]);
            Args = string.Join(" ", args);

            var host = new WebHostBuilder()
                .UseServer("Microsoft.AspNetCore.Server.Kestrel")
                .UseUrls(url.ToString())
                .UseStartup<Startup>()
                .Build();

            ServerCancellationTokenSource = new CancellationTokenSource();

            // shutdown server after 20s.
            var shutdownTask = Task.Run(async () =>
            {
                await Task.Delay(20000);
                ServerCancellationTokenSource.Cancel();
            });

            host.Run(ServerCancellationTokenSource.Token);
            shutdownTask.Wait();

            return 0;
        }
開發者ID:krwq,項目名稱:cli,代碼行數:31,代碼來源:Startup.cs

示例4: MiddlewareSkippedIfTokenIsMissing

        public async Task MiddlewareSkippedIfTokenIsMissing()
        {
            var assertsExecuted = false;

            var builder = new WebHostBuilder()
                .UseSetting("PORT", "12345")
                .UseSetting("APPL_PATH", "/")
                .UseIISIntegration()
                .Configure(app =>
                {
                    app.Run(context =>
                    {
                        var auth = context.Features.Get<IHttpAuthenticationFeature>();
                        Assert.Null(auth);
                        assertsExecuted = true;
                        return Task.FromResult(0);
                    });
                });
            var server = new TestServer(builder);

            var req = new HttpRequestMessage(HttpMethod.Get, "");
            req.Headers.TryAddWithoutValidation("MS-ASPNETCORE-TOKEN", "TestToken");
            var response = await server.CreateClient().SendAsync(req);
            Assert.True(assertsExecuted);
            response.EnsureSuccessStatusCode();
        }
開發者ID:aspnet,項目名稱:IISIntegration,代碼行數:26,代碼來源:IISMiddlewareTests.cs

示例5: Main

        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile(HostingJsonFileName, optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .AddCommandLine(args)
                .Build();

            var host = new WebHostBuilder()
                .UseConfiguration(configuration)
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseKestrel(
                    options =>
                    {
                        // TODO: for Kestrel to serve HTTPS, a certificate is required
                        //options.UseHttps()
                        // Do not add the Server HTTP header when using the Kestrel Web Server.
                        options.AddServerHeader = false;
                    })
                // $Start-WebServer-IIS$
                .UseIISIntegration()
                // $End-WebServer-IIS$
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
開發者ID:miroslavpopovic,項目名稱:timetracker,代碼行數:27,代碼來源:Program.cs

示例6: GetServer

 TestServer GetServer()
 {
   var bldr = new WebHostBuilder()
     .Configure(app => app.UseMetaWeblog("/livewriter"))
     .ConfigureServices( svcs => svcs.AddMetaWeblog<TestMetaWeblogService>());
   return new TestServer(bldr);
 }
開發者ID:shawnwildermuth,項目名稱:MetaWeblog,代碼行數:7,代碼來源:MethodFacts.cs

示例7: Main

        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .AddCommandLine(args)
                .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                .AddJsonFile("hosting.json", optional: true)
                .Build();

            var host = new WebHostBuilder()
                .UseConfiguration(config) // Default set of configurations to use, may be subsequently overridden 
              //.UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory()) // Override the content root with the current directory
                .UseUrls("http://*:1000", "https://*:902")
                .UseEnvironment("Development")
                .UseWebRoot("public")
                .ConfigureServices(services =>
                {
                    // Configure services that the application can see
                    services.AddSingleton<IMyCustomService, MyCustomService>();
                })
                .Configure(app =>
                {
                    // Write the application inline, this won't call any startup class in the assembly

                    app.Use(next => context =>
                    {
                        return next(context);
                    });
                })
                .Build();

            host.Run();
        }
開發者ID:akrisiun,項目名稱:Hosting,代碼行數:33,代碼來源:StartupFullControl.cs

示例8: Main

        public static void Main(string[] args)
        {
            try
            {
                var host = new WebHostBuilder()
                    .UseKestrel(options =>
                        {
                            options.UseHttps(@"..\..\certificates\localhost_ssl.pfx", "[email protected]");
                            options.NoDelay = true;

                            //I use this to get rid of SSL errors, feel free to remove it.
                            IConnectionFilter prevFilter = options.ConnectionFilter ?? new NoOpConnectionFilter();
                            options.ConnectionFilter = new IgnoreSslErrorsConnectionFilter(prevFilter);
                        }
                    )
                    .UseUrls("https://localhost:5000")
                    .UseContentRoot(Directory.GetCurrentDirectory());

                host.UseStartup<Startup>();

                var webHost = host.Build();

                webHost.Run();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }
        }
開發者ID:coupalm,項目名稱:PnP,代碼行數:30,代碼來源:Program.cs

示例9: Main

        public static void Main(string[] args)
        {
            var currentDirectory = Directory.GetCurrentDirectory();

            var host = new WebHostBuilder()
                .UseIISIntegration()
                .UseKestrel()
                .UseContentRoot(currentDirectory)
                .UseStartup<Startup>()
                .Build();

            using (host)
            {
                using (var cts = new CancellationTokenSource())
                {
                    host.Run((services) =>
                    {
                        var orchardHost = new OrchardHost(
                            services,
                            System.Console.In,
                            System.Console.Out,
                            args);

                        orchardHost
                            .RunAsync()
                            .Wait();

                        cts.Cancel();

                    }, cts.Token, "Application started. Press Ctrl+C to shut down.");
                }
            }
        }
開發者ID:vairam-svs,項目名稱:Orchard2,代碼行數:33,代碼來源:Program.cs

示例10: Main

        public static void Main(string[] args)
        {
            var configBuilder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("hosting.json");

            var configuration = configBuilder.Build();

            var hostBuilder = new WebHostBuilder();

            // set urls and environment
            hostBuilder
                .UseUrls(configuration["urls"])
                .UseEnvironment(configuration["environment"]);

            // set other common things
            hostBuilder
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>();

            var host = hostBuilder.Build();

            host.Run();
        }
開發者ID:kosmakoff,項目名稱:WebApiWithAuth,代碼行數:26,代碼來源:Program.cs

示例11: MiddlewareRejectsRequestIfTokenHeaderIsMissing

        public async Task MiddlewareRejectsRequestIfTokenHeaderIsMissing()
        {
            var assertsExecuted = false;

            var builder = new WebHostBuilder()
                .UseSetting("TOKEN", "TestToken")
                .UseSetting("PORT", "12345")
                .UseSetting("APPL_PATH", "/")
                .UseIISIntegration()
                .Configure(app =>
                {
                    app.Run(context =>
                    {
                        var auth = context.Features.Get<IHttpAuthenticationFeature>();
                        Assert.Null(auth);
                        assertsExecuted = true;
                        return Task.FromResult(0);
                    });
                });
            var server = new TestServer(builder);

            var req = new HttpRequestMessage(HttpMethod.Get, "");
            var response = await server.CreateClient().SendAsync(req);
            Assert.False(assertsExecuted);
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
開發者ID:aspnet,項目名稱:IISIntegration,代碼行數:26,代碼來源:IISMiddlewareTests.cs

示例12: InnerServiceNotAvailableOutsideIsolation

        public async Task InnerServiceNotAvailableOutsideIsolation() {
            // Arrange
            var builder = new WebHostBuilder()
                .Configure(app => {
                    app.Isolate(
                        // Configure the isolated pipeline.
                        map => { },

                        // Configure the isolated services.
                        services => services.AddSingleton(new ValueService("Dummy")));

                    app.Run(async context => {
                        var service = context.RequestServices.GetService<ValueService>();

                        await context.Response.WriteAsync(service?.Value ?? "<null>");
                    });
                });

            var server = new TestServer(builder);

            var client = server.CreateClient();

            // Act
            var response = await client.GetStringAsync("/");

            // Assert
            Assert.Equal("<null>", response);
        }
開發者ID:aspnet-contrib,項目名稱:AspNet.Hosting.Extensions,代碼行數:28,代碼來源:HostingExtensionsTests.cs

示例13: Main

 public static void Main(string[] args)
 {
     var host = new WebHostBuilder()
     .UseStartup<TestStartup>()
     .Build();
     host.Run();
 }
開發者ID:digipolisantwerp,項目名稱:serviceagents_aspnetcore,代碼行數:7,代碼來源:TestStartup.cs

示例14: Main

        public static void Main(string[] args)
        {
            if (Debugger.IsAttached)
            {
                Environment.SetEnvironmentVariable(
                    "ASPNETCORE_ENVIRONMENT", 
                    EnvironmentName.Development);
            }	    
	    
            var config = new ConfigurationBuilder()
                	  .AddJsonFile("hosting.json", optional: true)
        		  .AddEnvironmentVariables("ASPNETCORE_")
                	  .AddCommandLine(args)
                	  .Build();

            var host = new WebHostBuilder()
                        .UseKestrel()
                        .UseContentRoot(Directory.GetCurrentDirectory())
                        .UseConfiguration(config)
                        .UseIISIntegration()
                        .UseStartup<Startup>()
                        .Build();

            host.Run();
        }
開發者ID:rfinochi,項目名稱:confsamples,代碼行數:25,代碼來源:Program.cs

示例15: Main

        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .AddCommandLine(args)
                .Build();

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseConfiguration(config)
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            // Delete UNIX pipe if it exists at startup (eg. previous process crashed before cleaning it up)
            var addressFeature = host.ServerFeatures.Get<IServerAddressesFeature>();
            var url = ServerAddress.FromUrl(addressFeature.Addresses.First());
            if (url.IsUnixPipe && File.Exists(url.UnixPipePath))
            {
                Console.WriteLine("UNIX pipe {0} already existed, deleting it.", url.UnixPipePath);
                File.Delete(url.UnixPipePath);
            }

            host.Run();
        }
開發者ID:Daniel15,項目名稱:Website,代碼行數:25,代碼來源:Startup.cs


注:本文中的Microsoft.AspNetCore.Hosting.WebHostBuilder類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。