コード例 #1
0
ファイル: Program.cs プロジェクト: rgilmutdinov/DfmWeb
        public static void RunWebHost(bool isConsole)
        {
            string contentRoot = Directory.GetCurrentDirectory();

            if (!isConsole)
            {
                string modulePath = Process.GetCurrentProcess().MainModule.FileName;
                contentRoot = Path.GetDirectoryName(modulePath);
            }

            IWebHostBuilder hostBuilder = new WebHostBuilder();
            string          environment = hostBuilder.GetSetting(WebHostDefaults.EnvironmentKey);

            IConfigurationRoot hostingConfiguration = new ConfigurationBuilder()
                                                      .SetBasePath(contentRoot)
                                                      .AddJsonFile("hosting.json", true)
                                                      .AddJsonFile("appsettings.json", true)
                                                      .AddJsonFile($"appsettings.{environment}.json", true)
                                                      .Build();

            hostBuilder
            .UseKestrel(options =>
            {
                options.Limits.MaxRequestBodySize = null;
            })
            .UseConfiguration(hostingConfiguration)
            .UseContentRoot(contentRoot)
            .ConfigureLogging(log =>
            {
                log.AddConsole();
                log.AddDebug();
            })
            .UseIISIntegration()
            .UseStartup <Startup>();

            IWebHost host = hostBuilder.Build();

            if (isConsole)
            {
                host.Run();
            }
            else
            {
                host.RunAsService();
            }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: dev-thinks/SerilogWithDb
        private static LoggingLevelSwitch GetLoggingLevel()
        {
            var hostBuilder = new WebHostBuilder();
            var environment = hostBuilder.GetSetting("environment");

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                .AddJsonFile($"appsettings.{environment}.json", optional: true)
                                .AddEnvironmentVariables()
                                .Build();

            var  loggingLevel = new LoggingLevelSwitch();
            bool res          = Enum.TryParse <LogEventLevel>(configuration["DefaultLoggingLevel"], true, out var defaultLevel);

            loggingLevel.MinimumLevel = res ? defaultLevel : LogEventLevel.Information;

            return(loggingLevel);
        }
コード例 #3
0
        public static void Main(string[] args)
        {
            var hostBuilder = new WebHostBuilder()
                              .UseKestrel()
                              .UseIISIntegration()
                              .UseStartup <Startup>();

            // ConfigureServices is only used to delay execution until UseIISIntegration()
            // has actually set the "urls" setting.
            hostBuilder.ConfigureServices(services =>
            {
                var urls = hostBuilder.GetSetting("urls");
                urls     = urls.Replace("localhost", "127.0.0.1");
                hostBuilder.UseSetting("urls", urls);
            });

            var host = hostBuilder.Build();

            host.Run();
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: nabilcherifi/TUI
        /// <summary>
        /// doc
        /// </summary>
        /// <param name="args">permit to define arguments</param>
        /// <returns>permit to define result</returns>
        public static IWebHost BuildWebHost(string[] args)
        {
            var webHostBuilder = new WebHostBuilder();
            var env            = webHostBuilder.GetSetting("environment");

            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env}.json", optional: true)
                          .AddEnvironmentVariables();

            var configuration = builder.Build();

            var host = WebHost.CreateDefaultBuilder(args)
                       .UseKestrel()
                       .UseContentRoot(_pathToContentRoot)
                       .UseUrls(string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}", configuration["ServerName"], configuration["ServerPort"]))
                       .UseStartup <Startup>()
                       .Build();

            return(host);
        }
コード例 #5
0
        public void Launch()
        {
            var builder = new WebHostBuilder();

            builder.UseContentRoot(GetContentRootPath())
            .UseEnvironment(_environment)
            .ConfigureLogging(factory =>
            {
                factory.AddConsole();
            })
            .UseAutofacMultitenant((context, options) => {
                options.ValidateOnBuild = false;
                options.MapDefaultTenantToAllRootDomains();
                options.AddTenantsFromConfig(context.Configuration);
                options.ConfigureTenants(builder => {
                    builder.MapToTenantIdSubDomain();
                });
            })
            .UseConfiguration(_configBuilder.Invoke(_environment, builder.GetSetting(WebHostDefaults.ContentRootKey)))
            .UseStartup <T>()
            .ConfigureServices(services =>
            {
                services.AddAntiforgery(options => {
                    options.Cookie.Name   = AntiForgeryCookieName;
                    options.FormFieldName = AntiForgeryFieldName;
                });

                //Test Server Fix
                //https://github.com/aspnet/Hosting/issues/954
                //https://github.com/Microsoft/vstest/issues/428
                var assembly = typeof(T).GetTypeInfo().Assembly;
                services.ConfigureRazorViewEngineForTestServer(assembly, _netVersion);
            });

            _testServer = new Microsoft.AspNetCore.TestHost.TestServer(builder);

            Client = _testServer.CreateClient();
        }
コード例 #6
0
        public static void Main(string[] args)
        {
            // Vytvorit host
            var host = new WebHostBuilder();
            var env  = host.GetSetting("environment");

            // Nacitanie konfiguracie
            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                         .AddJsonFile($"appsettings.{env}.json", optional: true)
                         .Build();

            // Nastavenie host
            host.UseKestrel()
            .UseConfiguration(config)
            // Pouzit url z konfiguracie
            .UseUrls(config["server:urls"])
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup <Startup>()
            .Build()
            .Run();
        }
コード例 #7
0
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddEnvironmentVariables()
                         .AddCommandLine(args)
                         .Build();

            var home = config.GetValue(HomeKey, Directory.GetCurrentDirectory());

            var hostBuilder = new WebHostBuilder()
                              .UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());

            var environment = hostBuilder.GetSetting(WebHostDefaults.EnvironmentKey);

            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(home)
                                .AddJsonFile("config.json", false, true);

            if (!string.IsNullOrWhiteSpace(environment))
            {
                configBuilder.AddJsonFile($"config.{environment.ToLower()}.json", true, true);
            }

            var configuration = configBuilder
                                .AddCommandLine(args)
                                .Build();

            var host = hostBuilder
                       .UseKestrel()
                       .UseContentRoot(home)
                       .UseConfiguration(configuration)
                       .ConfigureServices(services => services.AddSingleton <IConfiguration>(configuration))
                       .UseStartup <Startup>()
                       .Build();

            host.Run();
        }
コード例 #8
0
        public static IWebHost BuildWebHost(string[] args)
        {
            var webHost     = new WebHostBuilder();
            var environment = webHost.GetSetting("environment");

            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: true)
                                //.AddJsonFile("appsettings.{environment}.json", optional: true)
                                .AddJsonFile("hosting.json", optional: true)
                                .AddCommandLine(args);

            if (environment == "Development")
            {
                configBuilder.AddUserSecrets <Startup>();
            }

            var config = configBuilder.Build();

            return(WebHost.CreateDefaultBuilder(args)
                   .UseConfiguration(config)
                   .UseStartup <Startup>()
                   .Build());
        }
コード例 #9
0
        private static IWebHost BuildWebHost(string[] args)
        {
            var webHostBuilder = new WebHostBuilder()
                                 .UseKestrel()
                                 .UseContentRoot(Directory.GetCurrentDirectory())
                                 .UseIISIntegration()
                                 .UseAzureAppServices();

            var contentRoot = webHostBuilder.GetSetting(WebHostDefaults.ContentRootKey);
            var environment = webHostBuilder.GetSetting(WebHostDefaults.EnvironmentKey);

            var isDevelopment = EnvironmentName.Development.Equals(environment);

            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(contentRoot)
                                       .AddJsonFile("appsettings.json", false, false);

            if (isDevelopment)
            {
                configurationBuilder = configurationBuilder
                                       .AddUserSecrets <Startup>();
            }

            var configuration = configurationBuilder
                                .AddEnvironmentVariables()
                                .Build();

            var serilogLevel = configuration.GetLoggingLevel("MinimumLevel:Default");

            var loggerConfiguration = new LoggerConfiguration()
                                      .ReadFrom.Configuration(configuration)
                                      .Enrich.FromLogContext()
                                      .Enrich.WithDemystifiedStackTraces();

            var appInsightsInstrumentationKey = configuration.GetApplicationInsightsInstrumentationKey();

            if (!string.IsNullOrEmpty(appInsightsInstrumentationKey))
            {
                loggerConfiguration = loggerConfiguration
                                      .WriteTo.ApplicationInsightsTraces(appInsightsInstrumentationKey, serilogLevel);

                webHostBuilder = webHostBuilder
                                 .UseDeveloperApplicationInsights(appInsightsInstrumentationKey);
            }
            else
            {
                TelemetryConfiguration.Active.DisableTelemetry = true;
            }

            if (isDevelopment)
            {
                loggerConfiguration = loggerConfiguration
                                      .WriteTo.Seq("http://localhost:5341/", serilogLevel)
                                      .WriteTo.Console(serilogLevel);
            }

            var logger = loggerConfiguration.CreateLogger();

            try
            {
                logger.Information("Starting Host...");

                return(webHostBuilder
                       .UseStartup <Startup>()
                       .UseConfiguration(configuration)
                       .UseSerilog(logger, true)
                       .Build());
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, "Host terminated unexpectedly");
                throw;
            }
        }
コード例 #10
0
        public static void Main(string[] args)
        {
            //Console.WriteLine("Empezamo a medir startup");
            var totalTime = Stopwatch.StartNew();

            var config = new ConfigurationBuilder()
                         .AddCommandLine(args)
                         .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                         .Build();

            var builder = new WebHostBuilder()
                          .UseConfiguration(config)
                          .UseIISIntegration()
                          .UseStartup("MusicStore");

            if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.WebListener", System.StringComparison.Ordinal))
            {
                var environment = builder.GetSetting("environment") ??
                                  Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

                if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal))
                {
                    // Set up NTLM authentication for WebListener like below.
                    // For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or
                    // modify the applicationHost.config to enable NTLM.
                    builder.UseWebListener(options =>
                    {
                        options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM;
                    });
                }
                else
                {
                    builder.UseWebListener();
                }
            }
            else
            {
                builder.UseKestrel();
            }

            var host = builder.Build();

            host.Start();

            totalTime.Stop();
            Console.WriteLine("Server started in {0}ms", totalTime.ElapsedMilliseconds);
            Console.WriteLine();

            long r;

            using (var client = new HttpClient())
            {
                Console.WriteLine("Starting request to http://localhost:5000");
                var requestTime = Stopwatch.StartNew();
                var response    = client.GetAsync("http://*****:*****@"C:\Users\t-guhuro\Source\Repos\JitBench\src\MusicStore\out.txt")))
            using (StreamWriter file = new StreamWriter(File.Create(@"out.txt")))
            {
                file.WriteLine(totalTime.ElapsedMilliseconds + " " + r);
                Console.WriteLine("Startup time and request time writen to out.txt.");
            }
        }
コード例 #11
0
        public static void Main(string[] args)
        {
            /* Visual Studio configures IIS Express to host a Kestrel server.
             * When we run the project, Visual Studio starts the IIS Express which in turn starts the Kestrel server, then launches a browser and points it to the IIS Express.
             * We serve a page from ASP.NET Core that redirects the browser from the IIS Express to the NG Development Server.
             */

            // Visual Studio writes Byte Order Mark when saves files.
            // Webpack fails reading such a package.json. +https://github.com/webpack/enhanced-resolve/issues/87
            // Athough the docs claim that VS is aware of the special case of package.json,
            // apparently VS fails to recognize the file when the template wizard saves it during the project creation.
            EnsurePackageJsonFileHasNoBom();

            var webHostBuilder = new WebHostBuilder();

            string ngServeOptions = GetNgServeOptions(webHostBuilder);

            // Run "ng serve". For ASP.NET applications the working directory is the project root.
            // TODO AF20170914 Assign explicitly ngProcess.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            var ngProcess = Process.Start("cmd.exe", "/k start ng.cmd serve"
                                          + (!String.IsNullOrWhiteSpace(ngServeOptions) ? " " + ngServeOptions : String.Empty)); // TODO AF20170914. Simplify: ngServeOptions??String.Empty

            var ngServerProtocol = GetNgServerProtocol(ngServeOptions);
            var ngServerPort     = GetNgServerPort(ngServeOptions);
            // An NG Develpment Server may have already been started manually from the Command Prompt. Check if that is the case.
            bool isNgServerPortAvailable = IsNgServerPortAvailable(ngServerPort);

            var startPage = (isNgServerPortAvailable
              ? (StartPage
                 .Replace("{{PollingUrl}}", ngServerProtocol == "https" ? PollingUrl : $"http://localhost:{ngServerPort}/")
                 .Replace("{{RedirectionPageUrl}}", RedirectionPageUrl)
                 .Replace("{{DebuggerWarning}}", (Debugger.IsAttached ? DebuggerWarning : String.Empty))
                 )
                             // Inform the developer how to specify another port.
              : PortUnavailableErrorPage
                             )
                            .Replace("{{StyleSection}}", StyleSection)
            ;

            var redirectionPage = RedirectionPage
                                  .Replace("{{NgServerProtocol}}", ngServerProtocol)
                                  .Replace("{{NgServerPort}}", ngServerPort.ToString());

            // We use a CancellationToken for shutting down the Kestrel server after the redirection page has been sent to the browser.
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken       = cancellationTokenSource.Token;

            var webHost = webHostBuilder
                          .UseKestrel()
                          .UseIISIntegration()
                          .Configure(app => app.Run(async context =>
            {
                switch (context.Request.Path.Value)
                {
                case "/":
                    await context.Response.WriteAsync(startPage);
                    break;

                case PollingUrl:
                    var isNgServerReady         = await IsNgServerReady(ngServerProtocol, ngServerPort, cancellationToken);
                    context.Response.StatusCode = isNgServerReady ? StatusCodes.Status204NoContent : StatusCodes.Status503ServiceUnavailable;
                    break;

                case RedirectionPageUrl:
                    await context.Response.WriteAsync(redirectionPage);
                    cancellationTokenSource.Cancel();
                    break;

                default:
                    context.Response.StatusCode = StatusCodes.Status404NotFound;
                    break;
                }
            }))
                          .Build()
            ;

            // When the profile is "IIS Express" this setting is present. Sometimes we face "{{AppName}}" as the active profile, which doesn't have this setting (its value returns "production"? default?). That "{{AppName}}" profile doesn't open a web browser, so we cannot redirect anyway.
            var environmentSetting      = webHostBuilder.GetSetting("environment");
            var isIISExpressEnvironment = !String.IsNullOrEmpty(environmentSetting) && (environmentSetting.ToLower() == "development");

            if (isIISExpressEnvironment)
            {
                webHost.Run(cancellationToken);
            }

            if (ngProcess != null)
            {
                ngProcess.WaitForExit();
                ngProcess.Dispose();
            }
        }
コード例 #12
0
 public string GetSetting(string key)
 {
     return(WebHostBuilder.GetSetting(key));
 }
コード例 #13
0
ファイル: ReplicaWebHost.cs プロジェクト: ongzhixian/Impulse
        public static IWebHostBuilder CreateDefaultBuilder(string[] args)
        {
            var builder = new WebHostBuilder();

            if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }

            if (args != null)
            {
                builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
            }

            builder
            .UseKestrel((builderContext, options) =>
            {
                // Notes on order of execution of ReplicaUseKestrel
                // 1) IWebHostBuilder ReplicaUseKestrel(this IWebHostBuilder hostBuilder, Action<WebHostBuilderContext, KestrelServerOptions> configureOptions)
                // 2) IWebHostBuilder ReplicaUseKestrel(this IWebHostBuilder hostBuilder)



                //IDictionary<string, Action<ReplicaEndpointConfiguration>> EndpointConfigurations
                //    = new Dictionary<string, Action<ReplicaEndpointConfiguration>>(0, StringComparer.OrdinalIgnoreCase);

                // options is KestrelServerOptions
                //ReplicaAdhoc.Configure(options, builderContext.Configuration.GetSection("Kestrel"));


                Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader kestrelConfigurationLoader =
                    options.Configure(builderContext.Configuration.GetSection("Kestrel"));
                //kestrelConfigurationLoader.Endpoint("Http", configureOptions =>
                //{
                //    configureOptions.ListenOptions.UseConnectionLogging();
                //    //
                //    configureOptions.ListenOptions.ConnectionAdapters.Add(new ReplicaLoggingConnectionAdapter(logger))
                //});


                //options.Listen(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 38493), listenOptions =>
                //{
                //    var loggerFactory = listenOptions.KestrelServerOptions.ApplicationServices.GetRequiredService<ILoggerFactory>();
                //    var logger = loggerName == null ? loggerFactory.CreateLogger<ReplicaLoggingConnectionAdapter>() : loggerFactory.CreateLogger(loggerName);
                //    listenOptions.ConnectionAdapters.Add(new ReplicaLoggingConnectionAdapter(logger));
                //});


                options.Configure(builderContext.Configuration.GetSection("Kestrel")).Endpoint("Http", configureOptions =>
                {
                    configureOptions.ListenOptions.UseConnectionLogging();
                    //
                    //configureOptions.ListenOptions.ConnectionAdapters.Add(new ReplicaLoggingConnectionAdapter(logger))
                });



                // Break to debug
                // System.Diagnostics.Debugger.Break();
            })
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            //.ConfigureLogging((hostingContext, logging) =>
            //{
            //    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            //    logging.AddConsole();
            //    logging.AddDebug();
            //    logging.AddEventSourceLogger();
            //})
            .ConfigureServices((hostingContext, services) =>
            {
                // Fallback
                services.PostConfigure <HostFilteringOptions>(options =>
                {
                    if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
                    {
                        // "AllowedHosts": "localhost;127.0.0.1;[::1]"
                        var hosts = hostingContext.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        // Fall back to "*" to disable.
                        options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
                    }
                });
                // Change notification
                services.AddSingleton <IOptionsChangeTokenSource <HostFilteringOptions> >(
                    new ConfigurationChangeTokenSource <HostFilteringOptions>(hostingContext.Configuration));

                services.AddTransient <IStartupFilter, ReplicaHostFilteringStartupFilter>();
            })
            .UseIIS()
            .UseIISIntegration()
            .UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            });

            return(builder);
        }
コード例 #14
0
        private static IWebHostBuilder Create
        (
            ICollection <Action <IConfiguration> > configuration,
            ICollection <Action <IServiceCollection> > configureServices,
            ICollection <Action <IApplicationBuilder> > configure
        )
        {
            T startup = null;
            IConfiguration      config = null;
            IHostingEnvironment env;
            IServiceCollection  services = null;

            var builder = new WebHostBuilder()
                          .ConfigureAppConfiguration((context, cb) =>
            {
                env = context.HostingEnvironment;
                var testSettings = BuildTestSettings(env.ContentRootPath, env.EnvironmentName);
                ConfigureAppConfiguration(env, testSettings, cb);
                config = cb.Build();
            })
                          .ConfigureServices(serviceCollection =>
            {
                services = serviceCollection;

                Debug.Assert(services != null);
                Debug.Assert(config != null);

                var serviceProvider = serviceCollection.BuildServiceProvider();
                Debug.Assert(serviceProvider != null);

                using (var container = new HarmonyContainer(serviceProvider))
                {
                    container.AddAspNetCore();

                    container.Register(serviceProvider);
                    container.Register(services);
                    container.Register(config);

                    startup = container.Resolve <T>();
                    Debug.Assert(startup != null);
                    foreach (var action in configuration)
                    {
                        action(config);
                    }

                    container.Register(startup);
                    container.InvokeMethod <T>("ConfigureServices");
                    foreach (var action in configureServices)
                    {
                        action(serviceCollection);
                    }
                }
            })
                          .Configure(app =>
            {
                Debug.Assert(services != null);
                Debug.Assert(config != null);
                Debug.Assert(startup != null);
                Debug.Assert(app != null);

                var serviceProvider = services.BuildServiceProvider();
                Debug.Assert(serviceProvider != null);

                using (var container = new HarmonyContainer(serviceProvider))
                {
                    container.AddAspNetCore();

                    container.Register(serviceProvider);
                    container.Register(services);
                    container.Register(config);
                    container.Register(startup);
                    container.Register(app);

                    container.InvokeMethod <T>("Configure");
                    foreach (var action in configure)
                    {
                        action(app);
                    }
                }
            });

            var applicationKey = builder.GetSetting(WebHostDefaults.ApplicationKey);
            var assemblyName   = applicationKey ?? typeof(T).Assembly.GetName().Name;

            if (applicationKey != assemblyName)
            {
                builder.UseSetting(WebHostDefaults.ApplicationKey, assemblyName);
            }

            return(builder);
        }
コード例 #15
0
        public static void Main(string[] args)
        {
            var scenarioName = "Unknown";
            var config       = new ConfigurationBuilder()
                               .AddCommandLine(args)
                               .Build();

            var builder = new WebHostBuilder()
                          .ConfigureLogging(loggingBuilder => loggingBuilder.AddConsole())
                          .UseConfiguration(config)
                          .UseContentRoot(Directory.GetCurrentDirectory())
                          .UseIISIntegration()
                          .UseStartup <Startup>();

            if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal))
            {
                scenarioName = "HttpSysServer";
                Console.WriteLine("Using HttpSys server");
                builder.UseHttpSys();
            }
            else if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT")))
            {
                // ANCM is hosting the process.
                // The port will not yet be configured at this point, but will also not require HTTPS.
                scenarioName = "AspNetCoreModule";
                Console.WriteLine("Detected ANCM, using Kestrel");
                builder.UseKestrel();
            }
            else
            {
                // Also check "server.urls" for back-compat.
                var urls = builder.GetSetting(WebHostDefaults.ServerUrlsKey) ?? builder.GetSetting("server.urls");
                builder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Empty);

                Console.WriteLine($"Using Kestrel, URL: {urls}");

                if (urls.Contains(";"))
                {
                    throw new NotSupportedException("This test app does not support multiple endpoints.");
                }

                var uri = new Uri(urls);

                builder.UseKestrel(options =>
                {
                    options.Listen(IPAddress.Loopback, uri.Port, listenOptions =>
                    {
                        if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
                        {
                            scenarioName = "Kestrel(SSL)";
                            var certPath = Path.Combine(AppContext.BaseDirectory, "TestResources", "testCert.pfx");
                            Console.WriteLine($"Using SSL with certificate: {certPath}");
                            listenOptions.UseHttps(certPath, "testPassword");
                        }
                        else
                        {
                            scenarioName = "Kestrel(NonSSL)";
                        }
                    });
                });
            }

            var host = builder.Build();

            AppDomain.CurrentDomain.UnhandledException += (_, a) =>
            {
                Console.WriteLine($"Unhandled exception (Scenario: {scenarioName}): {a.ExceptionObject.ToString()}");
            };

            Console.WriteLine($"Starting Server for Scenario: {scenarioName}");
            host.Run();
        }
コード例 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebHostBuilder"/> class with pre-configured defaults.
        /// </summary>
        /// <remarks>
        ///   The following defaults are applied to the returned <see cref="WebHostBuilder"/>:
        ///     use Kestrel as the web server and configure it using the application's configuration providers,
        ///     set the <see cref="IHostingEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/>,
        ///     load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
        ///     load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
        ///     load <see cref="IConfiguration"/> from environment variables,
        ///     load <see cref="IConfiguration"/> from supplied command line args,
        ///     configure the <see cref="ILoggerFactory"/> to log to the console and debug output,
        ///     and enable IIS integration.
        /// </remarks>
        /// <param name="args">The command line args.</param>
        /// <returns>The initialized <see cref="IWebHostBuilder"/>.</returns>
        public static IWebHostBuilder CreateDefaultBuilder(string[] args)
        {
            var builder = new WebHostBuilder();

            if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }
            if (args != null)
            {
                builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
            }

            builder.UseKestrel((builderContext, options) =>
            {
                options.Configure(builderContext.Configuration.GetSection("Kestrel"));
            })
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            })
            .ConfigureServices((hostingContext, services) =>
            {
                // Fallback
                services.PostConfigure <HostFilteringOptions>(options =>
                {
                    if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
                    {
                        // "AllowedHosts": "localhost;127.0.0.1;[::1]"
                        var hosts = hostingContext.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        // Fall back to "*" to disable.
                        options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
                    }
                });
                // Change notification
                services.AddSingleton <IOptionsChangeTokenSource <HostFilteringOptions> >(
                    new ConfigurationChangeTokenSource <HostFilteringOptions>(hostingContext.Configuration));

                services.AddTransient <IStartupFilter, HostFilteringStartupFilter>();
            })
            .UseIISIntegration()
            .UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            });

            return(builder);
        }
コード例 #17
0
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            var webHostBuilder = new WebHostBuilder();

            if (args?.Any() == true)
            {
                var config = new ConfigurationBuilder().AddCommandLine(args).Build();

                webHostBuilder.UseConfiguration(config);
            }

            // Kestrel
            webHostBuilder.UseKestrel((context, options) =>
            {
                options.AddServerHeader = false;

                var listenUrls = webHostBuilder.GetSetting(WebHostDefaults.ServerUrlsKey);

                if (string.IsNullOrWhiteSpace(listenUrls))
                {
                    // Load Kestrel Endpoint config in app setting
                    options.Configure(context.Configuration.GetSection("Kestrel"));
                }
            });

            // Content
            var contentRoot = webHostBuilder.GetSetting(WebHostDefaults.ContentRootKey);

            if (string.IsNullOrWhiteSpace(contentRoot))
            {
                webHostBuilder.UseContentRoot(Directory.GetCurrentDirectory());
            }

            // Capture Error
            webHostBuilder.CaptureStartupErrors(true);

            // DI Validate
            webHostBuilder.UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            });

            // App Config
            webHostBuilder.ConfigureAppConfiguration((context, configBuilder) =>
            {
                // Delete all default configuration providers
                configBuilder.Sources.Clear();

                configBuilder.SetBasePath(Directory.GetCurrentDirectory());

                configBuilder.AddJsonFile(ConfigurationFileName.AppSettings, true, true);

                var env = context.HostingEnvironment;

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));

                    if (appAssembly != null)
                    {
                        configBuilder.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                configBuilder.AddEnvironmentVariables();

                if (args?.Any() == true)
                {
                    configBuilder.AddCommandLine(args);
                }
            });

            // Service Config

            webHostBuilder.ConfigureServices((context, services) =>
            {
                // Hosting Filter

                services.PostConfigure <HostFilteringOptions>(options =>
                {
                    if (options.AllowedHosts != null && options.AllowedHosts.Count != 0)
                    {
                        return;
                    }

                    var hosts = context
                                .Configuration["AllowedHosts"]?
                                .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                    options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
                });

                // Hosting Filter Notification

                var hostingFilterOptions =
                    new ConfigurationChangeTokenSource <HostFilteringOptions>(context.Configuration);

                services.AddSingleton <IOptionsChangeTokenSource <HostFilteringOptions> >(hostingFilterOptions);

                services.AddTransient <IStartupFilter, HostFilteringStartupFilter>();

                // IIS
                var iisConfig = context.Configuration.GetSection("IIS");

                var isUseIis = iisConfig?.GetValue("IsUseIIS", false) ?? false;

                if (isUseIis)
                {
                    webHostBuilder.UseIIS();
                }

                var isUseIisIntegration = iisConfig?.GetValue("IsUseIISIntegration", false) ?? false;

                if (isUseIisIntegration)
                {
                    webHostBuilder.UseIISIntegration();
                }
            });

            // Startup
            webHostBuilder.UseStartup(PlatformServices.Default.Application.ApplicationName);

            return(webHostBuilder);
        }
コード例 #18
0
        public static void Main(string[] args)
        {
            Console.Title = "VideoReg.Api";
            //CreateWebHostBuilder(args).Build().Run();
            WebHostBuilder webHostBuilder = new WebHostBuilder();

            if (string.IsNullOrEmpty(webHostBuilder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                webHostBuilder.UseContentRoot(Directory.GetCurrentDirectory());
            }
            if (args != null)
            {
                webHostBuilder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
            }

            webHostBuilder.UseKestrel(delegate(WebHostBuilderContext builderContext, KestrelServerOptions options)
            {
                options.Configure(builderContext.Configuration.GetSection("Kestrel"));
            }).ConfigureAppConfiguration(delegate(WebHostBuilderContext hostingContext, IConfigurationBuilder config)
            {
                IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", optional: true, reloadOnChange: true);
                if (hostingEnvironment.IsDevelopment())
                {
                    Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
                    if (assembly != null)
                    {
                        config.AddUserSecrets(assembly, optional: true);
                    }
                }
                config.AddEnvironmentVariables();
                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            }).ConfigureLogging(delegate(WebHostBuilderContext hostingContext, ILoggingBuilder logging)
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();
            })
            .ConfigureServices(delegate(WebHostBuilderContext hostingContext, IServiceCollection services)
            {
                services.PostConfigure(delegate(HostFilteringOptions options)
                {
                    if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
                    {
                        string[] array = hostingContext.Configuration["AllowedHosts"]?.Split(new char[1]
                        {
                            ';'
                        }, StringSplitOptions.RemoveEmptyEntries);
                        options.AllowedHosts = ((array != null && array.Length != 0) ? array : new string[1]
                        {
                            "*"
                        });
                    }
                });
                services.AddSingleton((IOptionsChangeTokenSource <HostFilteringOptions>) new ConfigurationChangeTokenSource <HostFilteringOptions>(hostingContext.Configuration));
            })
            .UseDefaultServiceProvider(delegate(WebHostBuilderContext context, ServiceProviderOptions options)
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            });

            var host = webHostBuilder
                       .UseStartup <Startup>()
                       .Build();

            host.Run();
        }