Esempio n. 1
0
 private static void ConfigureWebBuilder(IWebHostBuilder webBuilder)
 {
     webBuilder.CaptureStartupErrors(true);
     webBuilder.UseDefaultServiceProvider(ConfigureServiceProvider);
     webBuilder.UseUrls("http://0.0.0.0:5000");
     webBuilder.UseStartup <Startup>();
 }
Esempio n. 2
0
        /// <summary>
        /// Configures the port and base path the server should listen on when running behind AspNetCoreModule.
        /// The app will also be configured to capture startup errors.
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IWebHostBuilder UseIISIntegration(this IWebHostBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            var port         = app.GetSetting(ServerPort) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPort}");
            var path         = app.GetSetting(ServerPath) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPath}");
            var pairingToken = app.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}");

            if (!string.IsNullOrEmpty(port) && !string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(pairingToken))
            {
                var address = "http://localhost:" + port + path;
                app.UseSetting(WebHostDefaults.ServerUrlsKey, address);
                app.CaptureStartupErrors(true);

                app.ConfigureServices(services =>
                {
                    services.AddSingleton <IStartupFilter>(new IISSetupFilter(pairingToken));
                    services.Configure <ForwardedHeadersOptions>(options =>
                    {
                        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                    });
                });
            }

            return(app);
        }
        /// <summary>
        /// Configures the port and base path the server should listen on when running behind AspNetCoreModule.
        /// The app will also be configured to capture startup errors.
        /// </summary>
        /// <param name="hostBuilder"></param>
        /// <returns></returns>
        public static IWebHostBuilder UseIIS(this IWebHostBuilder hostBuilder)
        {
            if (hostBuilder == null)
            {
                throw new ArgumentNullException(nameof(hostBuilder));
            }

            // Check if in process
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && NativeMethods.IsAspNetCoreModuleLoaded())
            {
                hostBuilder.CaptureStartupErrors(true);

                var iisConfigData = NativeMethods.HttpGetApplicationProperties();
                // Trim trailing slash to be consistent with other servers
                var contentRoot = iisConfigData.pwzFullApplicationPath.TrimEnd(Path.DirectorySeparatorChar);
                hostBuilder.UseContentRoot(contentRoot);
                return(hostBuilder.ConfigureServices(
                           services => {
                    services.AddSingleton(new IISNativeApplication(iisConfigData.pNativeApplication));
                    services.AddSingleton <IServer, IISHttpServer>();
                    services.AddSingleton <IStartupFilter>(new IISServerSetupFilter(iisConfigData.pwzVirtualApplicationPath));
                    services.AddAuthenticationCore();
                    services.Configure <IISServerOptions>(
                        options => { options.ForwardWindowsAuthentication = iisConfigData.fWindowsAuthEnabled || iisConfigData.fBasicAuthEnabled; }
                        );
                }));
            }

            return(hostBuilder);
        }
Esempio n. 4
0
 private static void UseStartup(IWebHostBuilder web)
 {
     web.CaptureStartupErrors(true)
     .UseSetting(WebHostDefaults.DetailedErrorsKey, "true")
     .UseContentRoot(Directory.GetCurrentDirectory())
     .UseIISIntegration()
     .UseStartup <Startup>();
 }
 void IHostingStartup.Configure(IWebHostBuilder builder)
 {
     builder.CaptureStartupErrors(true)
     .ConfigureAppConfiguration(ConfigureAppConfiguration)
     .ConfigureLogging(ConfigureLogging)
     .ConfigureServices(ConfigureService)
     .UseContentRoot(Directory.GetCurrentDirectory())
     .UseWebRoot("wwwroot")
     .UseIISIntegration()
     .Configure(Helper.Empty <IApplicationBuilder>());
 }
 public static IWebHostBuilder UseSharedAppSettings(this IWebHostBuilder builder, string environmentName, FileInfo sharedAppSettingsFileInfo)
 {
     builder.UseEnvironment(environmentName ?? EnvironmentName.Development);
     if (environmentName != EnvironmentName.Production)
     {
         builder.CaptureStartupErrors(true);
         builder.UseSetting("detailedErrors", "true");
     }
     builder.PrependSharedAppSettings(sharedAppSettingsFileInfo);
     return(builder);
 }
Esempio n. 7
0
 void IHostingStartup.Configure(IWebHostBuilder builder)
 {
     builder.CaptureStartupErrors(true)
     .UseSetting(WebHostDefaults.ApplicationKey, PlatformServices.Default.Application.ApplicationName)
     .ConfigureAppConfiguration(ConfigureAppConfiguration)
     .ConfigureLogging(ConfigureLogging)
     .ConfigureServices(ConfigureService)
     .UseContentRoot(Directory.GetCurrentDirectory())
     .UseWebRoot("wwwroot")
     .UseSetting(WebHostDefaults.DetailedErrorsKey, "true")
     .UseStartup <HostStartup>();
 }
        //.NET Core 2.2
        //public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        //    WebHost.CreateDefaultBuilder(args)
        //    .UseAutofacMultitenant((context,options) => {
        //        options.MapDefaultTenantToAllRootDomains();
        //        options.AddTenantsFromConfig(context.Configuration);
        //        options.ConfigureTenants(builder => {
        //            builder.MapToTenantIdSubDomain();
        //        });
        //    })

        //    //builder.UseDefaultServiceProvider((context, options) => {
        //    //    options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
        //    //    options.ValidateOnBuild = context.HostingEnvironment.IsDevelopment();
        //    //})

        //    .ConfigureAppConfiguration((context, config) =>
        //        {

        //            // JSON files, User secrets, environment variables and command line arguments
        //        })
        //    .ConfigureServices((hostContext, services) =>
        //    {
        //        //services.AddHostedService<ServiceA>();
        //    })
        //    .ConfigureWebHost(ConfigureWebHost);

        private static void ConfigureWebHost(IWebHostBuilder webBuilder)
        {
            webBuilder
            // These two settings allow an error page to be shown rather than throwing exception on startup
            // Need to be careful putting code after IWebHostBuilder.Build()
            .CaptureStartupErrors(true)
            //.UseSetting(WebHostDefaults.DetailedErrorsKey, "true") // Better to put this in appsettings. When enabled, or when the environment is Development, the app captures detailed errors.
            .UseShutdownTimeout(TimeSpan.FromSeconds(20))
            .ConfigureKestrel((context, options) =>
            {
                if (context.HostingEnvironment.IsDevelopment() || context.HostingEnvironment.IsIntegration())
                {
                    options.ListenAnyIP(5000);
                    options.ListenAnyIP(5001, listenOptions =>
                    {
                        //listenOptions.UseHttps(new X509Certificate2("certificates\\localhost.private.pfx", "password"));
                        listenOptions.UseHttps();
                    });
                }

                options.AllowSynchronousIO = true;
                options.AddServerHeader    = false;
            }
                              )
            //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.1
            .UseConfiguration(Configuration) //IWebHostBuilder configuration is added to the app's configuration, but the converse isn't true. ConfigureAppConfiguration doesn't affect the IWebHostBuilder configuration.
            .UseIISIntegration()
            .UseAzureKeyVault()
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
            })
            .ConfigureServices(services =>
            {
                services.AddHttpContextAccessor();
            })
            .LogApplicationParts()
            .LogViewLocations()
            .UseStartupTasks(false)
            //https://docs.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-3.0&tabs=visual-studio
            //When the app is published, the companion assets from all referenced projects and packages are copied into the wwwroot folder of the published app under _content/{LIBRARY NAME}/.
            //When running the consuming app from build output (dotnet run), static web assets are enabled by default in the Development environment. To support assets in other environments when running from build output, call UseStaticWebAssets on the host builder in Program.cs:
            //alling UseStaticWebAssets isn't required when running an app from published output (dotnet publish).
            .UseStaticWebAssets() //wwwroot from class library https://docs.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-3.0&tabs=visual-studio

            //.NET Core 2.2
            //https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/?fbclid=IwAR2SZoIsGjtTfwCd5bEG9n0mpnbo-3ERVCYZk6snBDnbIHwKC5dYbIoj_vY
            //.UseSerilog()
            //UseAzureAppServices() Azure Logging
            .UseStartup <TStartup>();
        }
Esempio n. 9
0
        //.NET Core 2.2
        //public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        //    WebHost.CreateDefaultBuilder(args)
        //    .UseAutofacMultitenant((context,options) => {
        //        options.MapDefaultTenantToAllRootDomains();
        //        options.AddTenantsFromConfig(context.Configuration);
        //        options.ConfigureTenants(builder => {
        //            builder.MapToTenantIdSubDomain();
        //        });
        //    })

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

        //    .ConfigureAppConfiguration((context, config) =>
        //        {

        //            // JSON files, User secrets, environment variables and command line arguments
        //        })
        //    .ConfigureServices((hostContext, services) =>
        //    {
        //        //services.AddHostedService<ServiceA>();
        //    })
        //    .ConfigureWebHost(ConfigureWebHost);

        private static void ConfigureWebHost(IWebHostBuilder webBuilder, string[] args)
        {
            webBuilder
            .CaptureStartupErrors(true) // These two settings allow an error page to be shown rather than throwing exception on startup in kestral. IIS has a StartupHook file which enables detailed errors in Development regardless of these settings. Hosted Services still execute when an exception is thrown!
            .UseSetting(WebHostDefaults.DetailedErrorsKey, new ConfigurationBuilder().AddInMemoryCollection(new Dictionary <string, string> {
                { HostDefaults.EnvironmentKey, Environments.Development }
            }).AddEnvironmentVariables("ASPNETCORE_").AddCommandLine(args ?? new string[0]).Build()["Environment"].Equals("Development", StringComparison.OrdinalIgnoreCase) ? "true" : "false")
            .UseShutdownTimeout(TimeSpan.FromSeconds(20))
            .ConfigureKestrel((context, options) =>
            {
                options.AllowSynchronousIO = true;
                options.AddServerHeader    = false;
            })
            //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.1
            //.UseConfiguration( //Host Config
            //new ConfigurationBuilder()
            //.AddInMemoryCollection(new Dictionary<string, string> { { HostDefaults.EnvironmentKey, Environments.Development } })
            //.SetBasePath(Directory.GetCurrentDirectory())
            //.AddJsonFile("hostsettings.json", optional: true)
            //.AddEnvironmentVariables(prefix: "ASPNETCORE_")
            //.AddCommandLine(args ?? new string[0])
            //.Build()
            //)
            .UseIISIntegration()
            .UseAzureKeyVault()
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
            })
            .ConfigureServices(services =>
            {
                services.AddHttpContextAccessor();
            })
            .LogApplicationParts()
            .LogViewLocations()
            .UseStartupTasks(false)
            //https://docs.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-3.0&tabs=visual-studio
            //When the app is published, the companion assets from all referenced projects and packages are copied into the wwwroot folder of the published app under _content/{LIBRARY NAME}/.
            //When running the consuming app from build output (dotnet run), static web assets are enabled by default in the Development environment. To support assets in other environments when running from build output, call UseStaticWebAssets on the host builder in Program.cs:
            //calling UseStaticWebAssets isn't required when running an app from published output (dotnet publish).
            .UseStaticWebAssets() //wwwroot from class library https://docs.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-3.0&tabs=visual-studio

            //.NET Core 2.2
            //https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/?fbclid=IwAR2SZoIsGjtTfwCd5bEG9n0mpnbo-3ERVCYZk6snBDnbIHwKC5dYbIoj_vY
            //.UseSerilog()
            //UseAzureAppServices() Azure Logging
            .UseStartup <TStartup>();
        }
Esempio n. 10
0
        /// <summary>
        /// Configures the port and base path the server should listen on when running behind AspNetCoreModule.
        /// The app will also be configured to capture startup errors.
        /// </summary>
        /// <param name="hostBuilder"></param>
        /// <returns></returns>
        public static IWebHostBuilder UseIISIntegration(this IWebHostBuilder hostBuilder)
        {
            if (hostBuilder == null)
            {
                throw new ArgumentNullException(nameof(hostBuilder));
            }

            // Check if `UseIISIntegration` was called already
            if (hostBuilder.GetSetting(nameof(UseIISIntegration)) != null)
            {
                return(hostBuilder);
            }

            var port         = hostBuilder.GetSetting(ServerPort) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPort}");
            var path         = hostBuilder.GetSetting(ServerPath) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPath}");
            var pairingToken = hostBuilder.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}");

            if (!string.IsNullOrEmpty(port) && !string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(pairingToken))
            {
                // Set flag to prevent double service configuration
                hostBuilder.UseSetting(nameof(UseIISIntegration), true.ToString());

                var address = "http://localhost:" + port;
                hostBuilder.CaptureStartupErrors(true);

                hostBuilder.ConfigureServices(services =>
                {
                    // Delay register the url so users don't accidently overwrite it.
                    hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, address);
                    services.AddSingleton <IStartupFilter>(new IISSetupFilter(pairingToken, new PathString(path)));
                    services.Configure <ForwardedHeadersOptions>(options =>
                    {
                        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;

                        // https://github.com/aspnet/IISIntegration/issues/140
                        // Azure Web Sites needs to be treated specially as we get an imbalanced set of X-Forwarded-* headers.
                        // We use the existence of the %WEBSITE_INSTANCE_ID% environment variable to determine if we're running
                        // in this environment, and if so we disable the symmetry check.
                        var isAzure = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"));
                        options.RequireHeaderSymmetry = !isAzure;
                    });
                });
            }

            return(hostBuilder);
        }
Esempio n. 11
0
        void IHostingStartup.Configure(IWebHostBuilder builder)
        {
            new HostingStartupProvider()
            .HostingStartups
            .Each(x => x.Configure(builder));

            builder.CaptureStartupErrors(true)
            .ConfigureAppConfiguration(ConfigureAppConfiguration)
            .ConfigureLogging(ConfigureLogging)
            .ConfigureServices(ConfigureService)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseWebRoot("wwwroot")
            //.RunIf(
            //    () => builder.GetSetting(WebHostDefaults.EnvironmentKey) == "Development",
            //    srv => srv.AddKestrelHttps())
            .UseSetting(WebHostDefaults.DetailedErrorsKey, "true")
            .UseStartup <Startup>();
        }
Esempio n. 12
0
        /// <summary>
        /// Runs at the end of services setup
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="args"></param>
        public static IWebHostBuilder SetupCommandInterception(IWebHostBuilder builder, string[] args)
        {
            builder.ConfigureServices(services =>
            {
                if (new CommandRunner(null).WillRunCommand(args))
                {
                    builder.CaptureStartupErrors(false);
                    var mi = typeof(HostingAbstractionsWebHostBuilderExtensions).GetMethod("SuppressStatusMessages", BindingFlags.Public | BindingFlags.Static);
                    if (mi != null)
                    {
                        mi.Invoke(null, new object[] { builder, true });
                    }
                    services.Add(ServiceDescriptor.Singleton(typeof(IStartupFilter), new InterceptRunStartupFilter(args)));
                }
            });

            return(builder);
        }
Esempio n. 13
0
        private static IWebHostBuilder SetupInProcessServer(IWebHostBuilder hostBuilder)
        {
            hostBuilder.UseSetting(nameof(UseIISIntegration), "true");
            hostBuilder.CaptureStartupErrors(true);

            var iisConfigData = NativeMethods.HttpGetApplicationProperties();

            hostBuilder.UseContentRoot(iisConfigData.pwzFullApplicationPath);
            return(hostBuilder.ConfigureServices(
                       services => {
                services.AddSingleton <IServer, IISHttpServer>();
                services.AddSingleton <IStartupFilter>(new IISServerSetupFilter(iisConfigData.pwzVirtualApplicationPath));
                services.AddAuthenticationCore();
                services.Configure <IISOptions>(
                    options => { options.ForwardWindowsAuthentication = iisConfigData.fWindowsAuthEnabled || iisConfigData.fBasicAuthEnabled; }
                    );
            }));
        }
        public static IWebHostBuilder UseCustomSerilogWebHostBuilder(this IWebHostBuilder webHostBuilder,
                                                                     IConfiguration configuration,
                                                                     string environment)
        {
            if (webHostBuilder == null)
            {
                throw new ArgumentNullException(nameof(webHostBuilder));
            }

            webHostBuilder.CaptureStartupErrors(false);
            webHostBuilder.ConfigureLogging((context, logging) => { logging.ClearProviders(); });

            webHostBuilder.ConfigureServices((context, collection) =>
            {
                collection.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
                collection.AddTransient <ClaimsValueEnricher>();
                collection.AddSingleton <ITelemetryInitializer>(s =>
                                                                new CloudRoleNameTelemetryInitializer(configuration["Logging:ApplicationInsights:RoleName"], configuration["Logging:ApplicationInsights:RoleInstance"]));

                var provider            = collection.BuildServiceProvider();
                var httpContextAccessor = provider.GetRequiredService <IHttpContextAccessor>();

                bool result = bool.TryParse(configuration["Logging:RedactSensitiveInformation"], out var redactSensitiveInformation);
                if (!result)
                {
                    redactSensitiveInformation = true;
                }

                LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
                                                          .ReadFrom.Configuration(configuration)
                                                          .Enrich.FromLogContext()
                                                          .Enrich.WithExceptionDetails()
                                                          .Destructure.UsingAttributes()
                                                          .Enrich.WithClaimsValueEnricher(provider, "businessAccountId", redactSensitiveInformation)
                                                          .Enrich.WithClaimsValueEnricher(provider, "userAccountId", redactSensitiveInformation)
                                                          .Enrich.WithClaimsValueEnricher(provider, "email", redactSensitiveInformation);

                Logger logger = loggerConfiguration.CreateLogger();
                collection.AddSingleton(services => (ILoggerFactory) new SerilogLoggerFactory(logger, true));
            });
            return(webHostBuilder);
        }
Esempio n. 15
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                //var descriptor = services.SingleOrDefault(
                //    d => d.ServiceType ==
                //        typeof(DbContextOptions<ApplicationDbContext>));
                //services.Remove(descriptor);
                //services.AddDbContext<ApplicationDbContext>(options =>
                //{
                //    options.UseInMemoryDatabase("InMemoryDbForTesting");
                //});

                var sp = services.BuildServiceProvider();
                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var logger         = scopedServices
                                         .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();

                    //var db = scopedServices.GetRequiredService<ApplicationDbContext>();
                    //db.Database.EnsureCreated();
                    //try
                    //{
                    //    Utilities.InitializeDbForTests(db);
                    //}
                    //catch (Exception ex)
                    //{
                    //    logger.LogError(ex, "An error occurred seeding the " +
                    //        "database with test messages. Error: {Message}", ex.Message);
                    //}
                }
            });

            builder.CaptureStartupErrors(true);
            builder.Configure(app =>
            {
                var logger = app.ApplicationServices.GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();
                LogMiddlleware(app, logger);
            });
        }
        /// <summary>
        /// Configures the port and base path the server should listen on when running behind AspNetCoreModule.
        /// The app will also be configured to capture startup errors.
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IWebHostBuilder UseIISIntegration(this IWebHostBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            var port         = app.GetSetting(ServerPort) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPort}");
            var path         = app.GetSetting(ServerPath) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPath}");
            var pairingToken = app.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}");

            if (!string.IsNullOrEmpty(port) && !string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(pairingToken))
            {
                var address = "http://localhost:" + port + path;
                app.UseSetting(WebHostDefaults.ServerUrlsKey, address);
                app.CaptureStartupErrors(true);

                app.ConfigureServices(services =>
                {
                    services.AddSingleton <IStartupFilter>(new IISSetupFilter(pairingToken));
                    services.Configure <ForwardedHeadersOptions>(options =>
                    {
                        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;

                        // https://github.com/aspnet/IISIntegration/issues/140
                        // Azure Web Sites needs to be treated specially as we get an imbalanced set of X-Forwarded-* headers.
                        // We use the existence of the %WEBSITE_INSTANCE_ID% environment variable to determine if we're running
                        // in this environment, and if so we disable the symmetry check.
                        var isAzure = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID"));
                        options.RequireHeaderSymmetry = !isAzure;
                    });
                });
            }

            return(app);
        }
Esempio n. 17
0
        /// <summary>
        /// Configures the port and base path the server should listen on when running behind AspNetCoreModule.
        /// The app will also be configured to capture startup errors.
        /// </summary>
        /// <param name="hostBuilder"></param>
        /// <returns></returns>
        public static IWebHostBuilder UseIISIntegration(this IWebHostBuilder hostBuilder)
        {
            if (hostBuilder == null)
            {
                throw new ArgumentNullException(nameof(hostBuilder));
            }

            // Check if `UseIISIntegration` was called already
            if (hostBuilder.GetSetting(nameof(UseIISIntegration)) != null)
            {
                return(hostBuilder);
            }

            // Check if in process
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && NativeMethods.is_ancm_loaded())
            {
                hostBuilder.UseSetting(nameof(UseIISIntegration), "true");
                hostBuilder.CaptureStartupErrors(true);

                // TODO consider adding a configuration load where all variables needed are loaded from ANCM in one call.
                var iisConfigData = new IISConfigurationData();
                var hResult       = NativeMethods.http_get_application_properties(ref iisConfigData);

                var exception = Marshal.GetExceptionForHR(hResult);
                if (exception != null)
                {
                    throw exception;
                }

                hostBuilder.UseContentRoot(iisConfigData.pwzFullApplicationPath);
                return(hostBuilder.ConfigureServices(services =>
                {
                    services.AddSingleton <IServer, IISHttpServer>();
                    services.AddSingleton <IStartupFilter>(new IISServerSetupFilter(iisConfigData.pwzVirtualApplicationPath));
                    services.AddAuthenticationCore();
                    services.Configure <IISOptions>(
                        options =>
                    {
                        options.ForwardWindowsAuthentication = iisConfigData.fWindowsAuthEnabled || iisConfigData.fBasicAuthEnabled;
                    }
                        );
                }));
            }

            var port                = hostBuilder.GetSetting(ServerPort) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPort}");
            var path                = hostBuilder.GetSetting(ServerPath) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPath}");
            var pairingToken        = hostBuilder.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}");
            var iisAuth             = hostBuilder.GetSetting(IISAuth) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{IISAuth}");
            var websocketsSupported = hostBuilder.GetSetting(IISWebSockets) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{IISWebSockets}");

            bool isWebSocketsSupported;

            if (!bool.TryParse(websocketsSupported, out isWebSocketsSupported))
            {
                // If the websocket support variable is not set, we will always fallback to assuming websockets are enabled.
                isWebSocketsSupported = (Environment.OSVersion.Version >= new Version(6, 2));
            }

            if (!string.IsNullOrEmpty(port) && !string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(pairingToken))
            {
                // Set flag to prevent double service configuration
                hostBuilder.UseSetting(nameof(UseIISIntegration), true.ToString());

                var enableAuth = false;
                if (string.IsNullOrEmpty(iisAuth))
                {
                    // back compat with older ANCM versions
                    enableAuth = true;
                }
                else
                {
                    // Lightup a new ANCM variable that tells us if auth is enabled.
                    foreach (var authType in iisAuth.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (!string.Equals(authType, "anonymous", StringComparison.OrdinalIgnoreCase))
                        {
                            enableAuth = true;
                            break;
                        }
                    }
                }

                var address = "http://127.0.0.1:" + port;
                hostBuilder.CaptureStartupErrors(true);

                hostBuilder.ConfigureServices(services =>
                {
                    // Delay register the url so users don't accidently overwrite it.
                    hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, address);
                    hostBuilder.PreferHostingUrls(true);
                    services.AddSingleton <IStartupFilter>(new IISSetupFilter(pairingToken, new PathString(path), isWebSocketsSupported));
                    services.Configure <ForwardedHeadersOptions>(options =>
                    {
                        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                    });
                    services.Configure <IISOptions>(options =>
                    {
                        options.ForwardWindowsAuthentication = enableAuth;
                    });
                    services.AddAuthenticationCore();
                });
            }

            return(hostBuilder);
        }
        /// <summary>
        /// Configures the port and base path the server should listen on when running behind AspNetCoreModule.
        /// The app will also be configured to capture startup errors.
        /// </summary>
        /// <param name="hostBuilder"></param>
        /// <returns></returns>
        public static IWebHostBuilder UseIISIntegration(this IWebHostBuilder hostBuilder)
        {
            if (hostBuilder == null)
            {
                throw new ArgumentNullException(nameof(hostBuilder));
            }

            // Check if `UseIISIntegration` was called already
            if (hostBuilder.GetSetting(nameof(UseIISIntegration)) != null)
            {
                return(hostBuilder);
            }

            // Check if in process
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && NativeMethods.is_ancm_loaded())
            {
                hostBuilder.UseSetting(nameof(UseIISIntegration), "true");
                hostBuilder.CaptureStartupErrors(true);

                var applicationPath = NativeMethods.http_get_application_full_path();
                hostBuilder.UseContentRoot(applicationPath);
                return(hostBuilder.ConfigureServices(services =>
                {
                    services.AddSingleton <IServer, IISHttpServer>();
                    services.AddAuthenticationCore();
                }));
            }

            var port         = hostBuilder.GetSetting(ServerPort) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPort}");
            var path         = hostBuilder.GetSetting(ServerPath) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPath}");
            var pairingToken = hostBuilder.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}");
            var iisAuth      = hostBuilder.GetSetting(IISAuth) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{IISAuth}");

            if (!string.IsNullOrEmpty(port) && !string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(pairingToken))
            {
                // Set flag to prevent double service configuration
                hostBuilder.UseSetting(nameof(UseIISIntegration), true.ToString());

                var enableAuth = false;
                if (string.IsNullOrEmpty(iisAuth))
                {
                    // back compat with older ANCM versions
                    enableAuth = true;
                }
                else
                {
                    // Lightup a new ANCM variable that tells us if auth is enabled.
                    foreach (var authType in iisAuth.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (!string.Equals(authType, "anonymous", StringComparison.OrdinalIgnoreCase))
                        {
                            enableAuth = true;
                            break;
                        }
                    }
                }

                var address = "http://localhost:" + port;
                hostBuilder.CaptureStartupErrors(true);

                hostBuilder.ConfigureServices(services =>
                {
                    // Delay register the url so users don't accidently overwrite it.
                    hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, address);
                    hostBuilder.PreferHostingUrls(true);
                    services.AddSingleton <IStartupFilter>(new IISSetupFilter(pairingToken, new PathString(path)));
                    services.Configure <ForwardedHeadersOptions>(options =>
                    {
                        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                    });
                    services.Configure <IISOptions>(options =>
                    {
                        options.ForwardWindowsAuthentication = enableAuth;
                    });
                    services.AddAuthenticationCore();
                });
            }

            return(hostBuilder);
        }
Esempio n. 19
0
        /// <summary>
        /// Configures the port and base path the server should listen on when running behind AspNetCoreModule.
        /// The app will also be configured to capture startup errors.
        /// </summary>
        /// <param name="hostBuilder"></param>
        /// <returns></returns>
        public static IWebHostBuilder UseIISIntegration(this IWebHostBuilder hostBuilder)
        {
            if (hostBuilder == null)
            {
                throw new ArgumentNullException(nameof(hostBuilder));
            }

            // Check if `UseIISIntegration` was called already
            if (hostBuilder.GetSetting(nameof(UseIISIntegration)) != null)
            {
                return(hostBuilder);
            }

            var port                = hostBuilder.GetSetting(ServerPort) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPort}");
            var path                = hostBuilder.GetSetting(ServerPath) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPath}");
            var pairingToken        = hostBuilder.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}");
            var iisAuth             = hostBuilder.GetSetting(IISAuth) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{IISAuth}");
            var websocketsSupported = hostBuilder.GetSetting(IISWebSockets) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{IISWebSockets}");

            bool isWebSocketsSupported;

            if (!bool.TryParse(websocketsSupported, out isWebSocketsSupported))
            {
                // If the websocket support variable is not set, we will always fallback to assuming websockets are enabled.
                isWebSocketsSupported = (Environment.OSVersion.Version >= new Version(6, 2));
            }

            if (!string.IsNullOrEmpty(port) && !string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(pairingToken))
            {
                // Set flag to prevent double service configuration
                hostBuilder.UseSetting(nameof(UseIISIntegration), true.ToString());

                var enableAuth = false;
                if (string.IsNullOrEmpty(iisAuth))
                {
                    // back compat with older ANCM versions
                    enableAuth = true;
                }
                else
                {
                    // Lightup a new ANCM variable that tells us if auth is enabled.
                    foreach (var authType in iisAuth.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (!string.Equals(authType, "anonymous", StringComparison.OrdinalIgnoreCase))
                        {
                            enableAuth = true;
                            break;
                        }
                    }
                }

                var address = "http://127.0.0.1:" + port;
                hostBuilder.CaptureStartupErrors(true);

                hostBuilder.ConfigureServices(services =>
                {
                    // Delay register the url so users don't accidentally overwrite it.
                    hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, address);
                    hostBuilder.PreferHostingUrls(true);
                    services.AddSingleton <IServerIntegratedAuth>(_ => new ServerIntegratedAuth()
                    {
                        IsEnabled            = enableAuth,
                        AuthenticationScheme = IISDefaults.AuthenticationScheme
                    });
                    services.AddSingleton <IStartupFilter>(new IISSetupFilter(pairingToken, new PathString(path), isWebSocketsSupported));
                    services.Configure <ForwardedHeadersOptions>(options =>
                    {
                        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                    });
                    services.Configure <IISOptions>(options =>
                    {
                        options.ForwardWindowsAuthentication = enableAuth;
                    });
                    services.AddAuthenticationCore();
                });
            }

            return(hostBuilder);
        }
 /// <summary>
 /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class
 /// needs to be configured in this method using the UseStartup<>() method.
 /// </summary>
 /// <param name="builder"></param>
 protected override void Init(IWebHostBuilder builder)
 {
     builder
     .CaptureStartupErrors(true)
     .UseStartup <Startup>();
 }