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

C# Hosting.WebHostBuilder类代码示例

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

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



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


示例16: HelloWorldMiddlewareTest

 static HelloWorldMiddlewareTest()
 {
     var builder = new WebHostBuilder();
     builder.UseStartup<HelloWorldMiddleware.Startup>();
     Server = new TestServer(builder);
     Client = Server.CreateClient();
 }
开发者ID:tuespetre,项目名称:mvc-sandbox,代码行数:7,代码来源:HelloWorldMiddlewareTest.cs


示例17: LargeContentMiddlewareTest

 static LargeContentMiddlewareTest()
 {
     var builder = new WebHostBuilder();
     builder.UseStartup<LargeContentMiddleware.Startup>();
     Server = new TestServer(builder);
     Client = Server.CreateClient();
 }
开发者ID:tuespetre,项目名称:mvc-sandbox,代码行数:7,代码来源:LargeContentMiddlewareTest.cs


示例18: BufferResponseWithManualContentLength_NotReplaced

        public async Task BufferResponseWithManualContentLength_NotReplaced()
        {
            var builder = new WebHostBuilder()
                .Configure(app =>
                {
                    app.UseResponseBuffering();
                    app.Run(async context =>
                    {
                        context.Response.ContentLength = 12;
                        Assert.False(context.Response.HasStarted);
                        Assert.True(context.Response.Body.CanSeek);
                        await context.Response.WriteAsync("Hello World");
                        Assert.False(context.Response.HasStarted);
                        Assert.True(context.Response.Body.CanSeek);
                    });
                });
            var server = new TestServer(builder);

            var response = await server.CreateClient().GetAsync("");
            response.EnsureSuccessStatusCode();
            Assert.Equal("Hello World", await response.Content.ReadAsStringAsync());

            IEnumerable<string> values;
            Assert.True(response.Content.Headers.TryGetValues("Content-Length", out values));
            Assert.Equal("12", values.FirstOrDefault());
        }
开发者ID:aspnet,项目名称:BasicMiddleware,代码行数:26,代码来源:ResponseBufferingMiddlewareTests.cs


示例19: XForwardedForDefaultSettingsChangeRemoteIpAndPort

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

            var builder = new WebHostBuilder()
                .Configure(app =>
                {
                    app.UseForwardedHeaders(new ForwardedHeadersOptions
                    {
                        ForwardedHeaders = ForwardedHeaders.XForwardedFor
                    });
                    app.Run(context =>
                    {
                        Assert.Equal("11.111.111.11", context.Connection.RemoteIpAddress.ToString());
                        Assert.Equal(9090, context.Connection.RemotePort);
                        // No Original set if RemoteIpAddress started null.
                        Assert.False(context.Request.Headers.ContainsKey("X-Original-For"));
                        // Should have been consumed and removed
                        Assert.False(context.Request.Headers.ContainsKey("X-Forwarded-For"));
                        assertsExecuted = true;
                        return Task.FromResult(0);
                    });
                });
            var server = new TestServer(builder);

            var req = new HttpRequestMessage(HttpMethod.Get, "");
            req.Headers.Add("X-Forwarded-For", "11.111.111.11:9090");
            await server.CreateClient().SendAsync(req);
            Assert.True(assertsExecuted);
        }
开发者ID:aspnet,项目名称:BasicMiddleware,代码行数:30,代码来源:ForwardedHeadersMiddlewareTest.cs


示例20: BigViewsTest

 static BigViewsTest()
 {
     var builder = new WebHostBuilder();
     builder.UseStartup<BigViews.Startup>();
     builder.UseProjectOf<BigViews.Startup>();
     Server = new TestServer(builder);
     Client = Server.CreateClient();
 }
开发者ID:tuespetre,项目名称:mvc-sandbox,代码行数:8,代码来源:BigViewsTest.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Http.DefaultHttpContext类代码示例发布时间:2022-05-26
下一篇:
C# TestHost.TestServer类代码示例发布时间: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