Beispiel #1
0
 public HttpPeer(string hostAndPort, HttpClient httpClient, IWebHostBuilder builder, IOcelotConfiguration config, IIdentityServerConfiguration identityServerConfiguration)
 {
     _identityServerConfiguration = identityServerConfiguration;
     _config                 = config;
     Id                      = hostAndPort;
     _hostAndPort            = hostAndPort;
     _httpClient             = httpClient;
     _jsonSerializerSettings = new JsonSerializerSettings()
     {
         TypeNameHandling = TypeNameHandling.All
     };
     _baseSchemeUrlAndPort = builder.GetSetting(WebHostDefaults.ServerUrlsKey);
 }
Beispiel #2
0
        public static IWebHostBuilder UseHealthChecks(this IWebHostBuilder builder, int port)
        {
            Guard.ArgumentValid(port > 0 && port < 65536, nameof(port), "Port must be a value between 1 and 65535");

            builder.ConfigureServices(services =>
            {
                var existingUrl = builder.GetSetting(WebHostDefaults.ServerUrlsKey);
                builder.UseSetting(WebHostDefaults.ServerUrlsKey, $"{existingUrl};http://localhost:{port}");

                services.AddSingleton <IStartupFilter>(new HealthCheckStartupFilter(port));
            });
            return(builder);
        }
Beispiel #3
0
        /// <summary>
        /// Configures the service to use the routes needed by Dapr Actor runtime.
        /// </summary>
        /// <param name="hostBuilder">The Microsoft.AspNetCore.Hosting.IWebHostBuilder to configure.</param>
        /// <param name="configure">A delegate used to register actors and configure the actor runtime.</param>
        /// <returns>The Microsoft.AspNetCore.Hosting.IWebHostBuilder.</returns>
        public static IWebHostBuilder UseActors(this IWebHostBuilder hostBuilder, Action <ActorRuntimeOptions> configure)
        {
            if (hostBuilder == null)
            {
                throw new ArgumentNullException("hostBuilder");
            }

            hostBuilder.ConfigureServices(services =>
            {
                if (configure != null)
                {
                    services.Configure <ActorRuntimeOptions>(configure);
                }
            });

            // Check if 'UseActors' has already been called.
            if (hostBuilder.GetSetting(SettingName) != null && hostBuilder.GetSetting(SettingName).Equals(true.ToString(), StringComparison.Ordinal))
            {
                return(hostBuilder);
            }

            // Set flag to prevent double service configuration
            hostBuilder.UseSetting(SettingName, true.ToString());

            hostBuilder.ConfigureServices(services =>
            {
                // Add routes.
                services.AddRouting();
                services.AddHealthChecks();
                services.AddSingleton <IStartupFilter>(new DaprActorSetupFilter());

                services.AddSingleton <ActorRuntime>(s =>
                {
                    return(new ActorRuntime(s.GetRequiredService <IOptions <ActorRuntimeOptions> >().Value, s.GetRequiredService <ILoggerFactory>()));
                });
            });

            return(hostBuilder);
        }
        /// <summary>
        /// Add Jasper to an ASP.Net Core application with optional configuration to Jasper
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="overrides">Programmatically configure Jasper options</param>
        /// <param name="configure">Programmatically configure Jasper options using the application's IConfiguration and IHostingEnvironment</param>
        /// <returns></returns>
        public static IWebHostBuilder UseJasper(this IWebHostBuilder builder, Action <JasperRegistry> overrides = null, Action <WebHostBuilderContext, JasperOptions> configure = null)
        {
            var registry = new JasperRegistry(builder.GetSetting(WebHostDefaults.ApplicationKey));

            overrides?.Invoke(registry);

            if (configure != null)
            {
                registry.Settings.Messaging(configure);
            }

            return(builder.UseJasper(registry));
        }
Beispiel #5
0
        /// <summary>
        /// 此处是Web程序的入口
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            //Kerstrel

            IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args)
                                      .UseKestrel()
                                      .UseIIS()
                                      .UseIISIntegration() //作为反向代理
                                      .UseEnvironment("Preview")
                                                           //.UseStartup<Startup>() //使用StartUp

                                      .UseUrls("http://localhost:6500");

            //在BUILDER上操作配置服务器

            //自定义JSON配置文件

            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.SetBasePath(builder.GetSetting(WebHostDefaults.ContentRootKey));
            configurationBuilder.AddJsonFile("appsettings.json");

            IConfiguration config = configurationBuilder.Build();
            var            value  = config["KEY"];

            builder.UseConfiguration(configurationBuilder.Build());

            //无StrartUp自定义congfig配置
            builder.ConfigureServices(service =>
            {
                //Add Service
            });
            builder.Configure(app =>
            {
                app.Run(async context => { await context.Response.WriteAsync("Pipeline Break!"); });
            });

            var host = builder.Build();


            using (IServiceScope scope = host.Services.CreateScope())
            {
                //此处获取服务的实例对象
                IWebHostEnvironment environment = scope.ServiceProvider.GetRequiredService <IWebHostEnvironment>();

                environment.ApplicationName = "我的新MVC服务APP";
            }


            host.Run();
        }
        public static IWebHostBuilder UseBenchmarksConfiguration(this IWebHostBuilder builder, IConfiguration configuration)
        {
            builder.UseConfiguration(configuration);

            // Handle the transport type
            var webHost = builder.GetSetting("KestrelTransport");

            // Handle the thread count
            var threadCountRaw = builder.GetSetting("threadCount");
            int?theadCount     = null;

            if (!string.IsNullOrEmpty(threadCountRaw) &&
                Int32.TryParse(threadCountRaw, out var value))
            {
                theadCount = value;
            }

            if (string.Equals(webHost, "LinuxTransport", StringComparison.OrdinalIgnoreCase))
            {
                builder.ConfigureServices(services =>
                {
                    services.Configure <KestrelServerOptions>(options =>
                    {
                        // Run callbacks on the transport thread
                        options.ApplicationSchedulingMode = SchedulingMode.Inline;
                    });
                })
                .UseLinuxTransport(options =>
                {
                    if (theadCount.HasValue)
                    {
                        options.ThreadCount = theadCount.Value;
                    }
                });
            }

            return(builder);
        }
Beispiel #7
0
        //public static IWebHostEnvironment Envir { get; }

        //public LoggerStartupAssembly() : this(Envir)
        //{

        //}
        //public LoggerStartupAssembly(IWebHostEnvironment env)
        //{
        //    Console.WriteLine(env.EnvironmentName);

        //}

        public void Configure(IWebHostBuilder builder)
        {
            //builder.ConfigureServices(services =>
            //{
            //    services.AddScoped<IEmailService, EmailService>();
            //    var x1 = builder.GetSetting("Environment");
            //    var x2 = builder.GetSetting("EnvironmentKey");

            //});
            var x3 = builder.GetSetting("Environment");
            //var x4 = builder.GetSetting("EnvironmentKey");

            //throw new NotImplementedException();
        }
Beispiel #8
0
        public static IWebHostBuilder ConfigureAppMetricsHostingConfiguration(
            this IWebHostBuilder hostBuilder,
            Action <MetricsEndpointsHostingOptions> setupHostingConfiguration)
        {
            var metricsEndpointHostingOptions = new MetricsEndpointsHostingOptions();

            setupHostingConfiguration(metricsEndpointHostingOptions);

            var ports = new List <int>();

            if (metricsEndpointHostingOptions.AllEndpointsPort.HasValue)
            {
                Console.WriteLine($"Hosting {metricsEndpointHostingOptions.MetricsEndpoint} on port {metricsEndpointHostingOptions.AllEndpointsPort.Value}");
                Console.WriteLine($"Hosting {metricsEndpointHostingOptions.MetricsTextEndpoint} endpoint on port {metricsEndpointHostingOptions.AllEndpointsPort.Value}");
                Console.WriteLine($"Hosting {metricsEndpointHostingOptions.EnvironmentInfoEndpoint} endpoint on port {metricsEndpointHostingOptions.AllEndpointsPort.Value}");

                ports.Add(metricsEndpointHostingOptions.AllEndpointsPort.Value);
            }
            else
            {
                if (metricsEndpointHostingOptions.MetricsEndpointPort.HasValue)
                {
                    Console.WriteLine($"Hosting {metricsEndpointHostingOptions.MetricsEndpoint} on port {metricsEndpointHostingOptions.MetricsEndpointPort.Value}");
                    ports.Add(metricsEndpointHostingOptions.MetricsEndpointPort.Value);
                }

                if (metricsEndpointHostingOptions.MetricsTextEndpointPort.HasValue)
                {
                    Console.WriteLine($"Hosting {metricsEndpointHostingOptions.MetricsTextEndpoint} endpoint on port {metricsEndpointHostingOptions.MetricsTextEndpointPort.Value}");
                    ports.Add(metricsEndpointHostingOptions.MetricsTextEndpointPort.Value);
                }

                if (metricsEndpointHostingOptions.EnvironmentInfoEndpointPort.HasValue)
                {
                    Console.WriteLine($"Hosting {metricsEndpointHostingOptions.EnvironmentInfoEndpoint} endpoint on port {metricsEndpointHostingOptions.EnvironmentInfoEndpointPort.Value}");
                    ports.Add(metricsEndpointHostingOptions.EnvironmentInfoEndpointPort.Value);
                }
            }

            if (ports.Any())
            {
                var existingUrl    = hostBuilder.GetSetting(WebHostDefaults.ServerUrlsKey);
                var additionalUrls = string.Join(";", ports.Distinct().Select(p => $"http://localhost:{p}/"));
                hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, $"{existingUrl};{additionalUrls}");
            }

            hostBuilder.ConfigureServices(services => services.Configure(setupHostingConfiguration));

            return(hostBuilder);
        }
Beispiel #9
0
        public static IWebHostBuilder UseBenchmarksConfiguration(this IWebHostBuilder builder, IConfiguration configuration)
        {
            builder.UseConfiguration(configuration);

            // Handle the transport type
            var webHost = builder.GetSetting("KestrelTransport");

            // Handle the thread count
            var threadCountRaw = builder.GetSetting("threadCount");
            int?theadCount     = null;

            if (!string.IsNullOrEmpty(threadCountRaw) &&
                Int32.TryParse(threadCountRaw, out var value))
            {
                theadCount = value;
            }

            if (string.Equals(webHost, "Sockets", StringComparison.OrdinalIgnoreCase))
            {
                builder.UseSockets(options =>
                {
                    if (theadCount.HasValue)
                    {
                        options.IOQueueCount = theadCount.Value;
                    }
                });
            }
            else if (string.Equals(webHost, "LinuxTransport", StringComparison.OrdinalIgnoreCase))
            {
                builder.UseLinuxTransport(options =>
                {
                    options.ApplicationSchedulingMode = PipeScheduler.Inline;
                });
            }

            return(builder);
        }
Beispiel #10
0
            public void Configure(IWebHostBuilder builder)
            {
                var loggerProvider = new TestLoggerProvider();

                builder.UseSetting("testhostingstartup", "0")
                .UseSetting("testhostingstartup_chain", builder.GetSetting("testhostingstartup_chain") + "0")
                .ConfigureServices(services => services.AddSingleton <ServiceA>())
                .ConfigureServices(services => services.AddSingleton <ITestSink>(loggerProvider.Sink))
                .ConfigureLogging((_, lf) => lf.AddProvider(loggerProvider))
                .ConfigureAppConfiguration((context, configurationBuilder) => configurationBuilder.AddInMemoryCollection(
                                               new[]
                {
                    new KeyValuePair <string, string>("testhostingstartup:config", "value")
                }));
            }
        /// <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);
        }
        /// <summary>
        /// Adds in middleware that detects reverse proxies and modifies the ASP.Net context appropriately.
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IWebHostBuilder UseReverseProxyRewrite(this IWebHostBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            // check if UseReverseProxyRewrite was called already
            if (builder.GetSetting(nameof(UseReverseProxyRewrite)) != null)
            {
                return(builder);
            }

            builder.UseSetting(nameof(UseReverseProxyRewrite), true.ToString());
            return(builder.ConfigureServices(services => services.AddSingleton <IStartupFilter>(new ReverseProxyRewriteSetupFilter())));
        }
Beispiel #13
0
        private static string GetContentRoot(IWebHostBuilder hostBuilder)
        {
            var    environment = hostBuilder.GetSetting(WebHostDefaults.EnvironmentKey);
            string contentRoot;

            if (string.Equals(environment, EnvironmentName.Development, StringComparison.OrdinalIgnoreCase))
            {
                contentRoot = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName;// @"..\..\..\..\..\UserManagement";
            }
            else
            {
                // But if we're published out, then we need to grab from the exe location.
                contentRoot = GetExePath();
            }

            return(contentRoot);
        }
        public ServiceFabricWebHostBuilder(string[] args)
        {
            Console.WriteLine("ServiceFabricWebHostBuilder: Constructor");

            _builder = new WebHostBuilder()
                       .UseDefaultHostingConfiguration(args);

            RunInServiceFabric = string.Equals(_builder.GetSetting("fabric"), "true", StringComparison.OrdinalIgnoreCase);

            Console.WriteLine("RunInServiceFabric: " + RunInServiceFabric);

            if (RunInServiceFabric)
            {
                _fabricRuntime = FabricRuntime.Create();
                Console.WriteLine("FabricRuntime initialized");
            }
        }
Beispiel #15
0
        private static bool SetContentRootFromSetting(IWebHostBuilder builder)
        {
            // Attempt to look for TEST_CONTENTROOT_APPNAME in settings. This should result in looking for
            // ASPNETCORE_TEST_CONTENTROOT_APPNAME environment variable.
            var assemblyName  = typeof(TEntryPoint).Assembly.GetName().Name;
            var settingSuffix = assemblyName.ToUpperInvariant().Replace(".", "_");
            var settingName   = $"TEST_CONTENTROOT_{settingSuffix}";

            var settingValue = builder.GetSetting(settingName);

            if (settingValue == null)
            {
                return(false);
            }

            builder.UseContentRoot(settingValue);
            return(true);
        }
Beispiel #16
0
        public static IWebHostBuilder UseHttpSysOrIISIntegration(this IWebHostBuilder builder)
        {
            if (builder.GetSetting("UseIISIntegration") == null)
            {
                // Self hosted
                builder.UseHttpSys(options =>
                {
                    options.Authentication.Schemes = AuthenticationSchemes.NTLM |
                                                     AuthenticationSchemes.Negotiate;
                    //options.Authentication.AllowAnonymous = false;
                    //options.MaxConnections = 100;
                    //options.MaxRequestBodySize = 30000000;
                    options.UrlPrefixes.Add("http://+:5000");
                });
            }

            return(builder);
        }
Beispiel #17
0
        private static string GetContentRoot(IWebHostBuilder hostBuilder)
        {
            var    environment = hostBuilder.GetSetting(WebHostDefaults.EnvironmentKey);
            string contentRoot;

            if (string.Equals(environment, EnvironmentName.Development, StringComparison.OrdinalIgnoreCase))
            {
                // We're using the IdentityServer project as the root.
                contentRoot = @"..\..\..\..\UserManagement";
            }
            else
            {
                // But if we're published out, then we need to grab from the exe location.
                contentRoot = GetExePath();
            }

            return(contentRoot);
        }
    public static void ConfigureWebHost(IWebHostBuilder builder, Func <string, string?> getSetting, Type?motorStartup)
    {
        IMotorStartup?startup = null;

        if (motorStartup is not null)
        {
            startup = Activator.CreateInstance(motorStartup) as IMotorStartup;
        }

        var          urls       = builder.GetSetting(WebHostDefaults.ServerUrlsKey);
        const string defaultUrl = "http://0.0.0.0:9110";

        if (string.IsNullOrEmpty(urls))
        {
            builder.UseUrls(defaultUrl);
        }
        else if (!urls.Contains(defaultUrl))
        {
            builder.UseUrls($"{urls};{defaultUrl}");
        }

        builder.Configure((context, applicationBuilder) =>
        {
            applicationBuilder.UseRouting();
            var enablePrometheusSetting = getSetting(MotorHostDefaults.EnablePrometheusEndpointKey);
            if (string.IsNullOrEmpty(enablePrometheusSetting) || bool.Parse(enablePrometheusSetting))
            {
                applicationBuilder.UsePrometheusServer();
            }

            startup?.Configure(context, applicationBuilder);
            applicationBuilder.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/health"); });
        });
        if (motorStartup is not null)
        {
            builder.UseSetting(WebHostDefaults.ApplicationKey, motorStartup.Assembly.GetName().Name);
        }

        builder.ConfigureServices((context, collection) =>
        {
            startup?.ConfigureServices(context, collection);
        });
    }
Beispiel #19
0
        /// <summary>
        /// 注册真实IP
        /// </summary>
        /// <param name="hostBuilder">Web主机生成器</param>
        /// <param name="headerKey">请求头键名</param>
        public static IWebHostBuilder UseRealIp(this IWebHostBuilder hostBuilder, string headerKey = "X-Forwarded-For")
        {
            if (hostBuilder == null)
            {
                throw new ArgumentNullException(nameof(hostBuilder));
            }
            if (hostBuilder.GetSetting(nameof(UseRealIp)) != null)
            {
                return(hostBuilder);
            }
            hostBuilder.UseSetting(nameof(UseRealIp), true.ToString());

            hostBuilder.ConfigureServices(services =>
            {
                services.AddSingleton <IStartupFilter>(new RealIpFilter());
                services.Configure <RealIpOptions>(options => options.HeaderKey = headerKey);
            });

            return(hostBuilder);
        }
        public static IWebHostBuilder UseBenchmarksConfiguration(this IWebHostBuilder builder, IConfiguration configuration)
        {
            builder.UseConfiguration(configuration);

            builder.UseSockets(options =>
            {
                if (int.TryParse(builder.GetSetting("threadCount"), out int threadCount))
                {
                    options.IOQueueCount = threadCount;
                }

#if NETCOREAPP5_0 || NET5_0
                options.WaitForDataBeforeAllocatingBuffer = false;

                Console.WriteLine($"Options: WaitForData={options.WaitForDataBeforeAllocatingBuffer}, IOQueue={options.IOQueueCount}");
#endif
            });

            return(builder);
        }
        public ServiceFabricWebHostBuilder(string[] args)
        {
            Console.WriteLine("ServiceFabricWebHostBuilder: Constructor");

            var config = new ConfigurationBuilder()
                .AddCommandLine(args)
                .Build();

            _builder = new WebHostBuilder()
                .UseConfiguration(config);

            RunInServiceFabric = string.Equals(_builder.GetSetting("fabric"), "true", StringComparison.OrdinalIgnoreCase);

            Console.WriteLine("RunInServiceFabric: " + RunInServiceFabric);

            if (RunInServiceFabric)
            {
                _fabricRuntime = FabricRuntime.Create();
                Console.WriteLine("FabricRuntime initialized");
            }
        }
        public static IWebHostBuilder UseBenchmarksConfiguration(this IWebHostBuilder builder, IConfiguration configuration)
        {
            builder.UseConfiguration(configuration);

            builder.UseSockets(options =>
            {
                if (int.TryParse(builder.GetSetting("threadCount"), out int threadCount))
                {
                    options.IOQueueCount = threadCount;
                }

                options.WaitForDataBeforeAllocatingBuffer = false;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    options.UnsafePreferInlineScheduling = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS") == "1";
                }

                Console.WriteLine($"Options: WaitForData={options.WaitForDataBeforeAllocatingBuffer}, PreferInlineScheduling={options.UnsafePreferInlineScheduling}, IOQueue={options.IOQueueCount}");
            });

            return(builder);
        }
Beispiel #23
0
        /// <summary>
        /// 加载工作流主机配置文件
        /// </summary>
        /// <param name="webHostBuilder"></param>
        /// <returns></returns>
        public static IWebHostBuilder ConfigurationWorkflowWebHost(this IWebHostBuilder webHostBuilder)
        {
            string root = AppDomain.CurrentDomain.BaseDirectory;

            string jsonFile = Path.Combine(root, "resources", "activiti.cfg.json");

            string appName = new ConfigurationBuilder().AddJsonFile(jsonFile).Build().GetValue <string>("applicationName");

            if (!string.IsNullOrWhiteSpace(appName))
            {
                string appKey = webHostBuilder.GetSetting(WebHostDefaults.ApplicationKey);

                webHostBuilder.UseSetting(WebHostDefaults.ApplicationKey, appName);
            }

            return(webHostBuilder.ConfigureAppConfiguration((ctx, builder) =>
            {
                ProcessEngineOption.ConfigFileName = jsonFile;

                builder.AddJsonFile(new PhysicalFileProvider(Path.Combine(root, "resources")), "activiti.cfg.json", false, true);
            }));
        }
Beispiel #24
0
        private static void SetupLocalCertificationSettings(IWebHostBuilder webHostBuilder)
        {
            var file = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, CertFile));

            if (File.Exists(file))
            {
                var certificate = new X509Certificate2(file);
                webHostBuilder.UseKestrel(
                    options =>
                {
                    var port = webHostBuilder.GetSetting("HTTPS_PORT");
                    options.Listen(IPAddress.Loopback, int.Parse(port), listenOptions =>
                    {
                        listenOptions.UseHttps(certificate);
                    });
                });
            }
            else
            {
                Console.WriteLine("Local cert not found! Please download it from Azure Portal to your tmp folder and try again or you may have cert issues!");
            }
        }
        public static IWebHostBuilder UsePaperSettings(this IWebHostBuilder builder, Action <PaperSettingsBuilder> action)
        {
            var settingsBuilder = new PaperSettingsBuilder();

            action.Invoke(settingsBuilder);

            var settings = (PaperSettings)settingsBuilder.Build();

            var baseUri = builder.GetSetting(WebHostDefaults.ServerUrlsKey);

            settings.BaseUri = (baseUri != null) ? new Uri(baseUri) : null;

            builder.ConfigureServices(services =>
                                      services.AddSingleton <IPaperSettings>(settings)
                                      );

            var exePath     = typeof(AspNetCoreExtensions).Assembly.Location;
            var contentPath = Path.GetDirectoryName(exePath);

            builder.UseContentRoot(contentPath);

            return(builder);
        }
Beispiel #26
0
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            IWebHostBuilder builder     = WebHost.CreateDefaultBuilder(args);
            string          environment = builder.GetSetting("environment");

            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .SetBasePath(Directory.GetCurrentDirectory())
                                               .AddJsonFile("hosting.json", true, true)
                                               .AddJsonFile($"hosting.{environment}.json", true, true)
                                               .Build();

            return(builder
                   .UseLibuv()
                   .UseUrls("http://localhost:5000")
                   .ConfigureAppConfiguration((context, config) =>
            {
                IWebHostEnvironment env = context.HostingEnvironment;
                if (env.IsDevelopment() || env.IsEnvironment("Testing"))
                {
                    config.AddJsonFile("appsettings.user.json", true);
                }
                else
                {
                    config.AddJsonFile("secrets.json", true, true);
                }
                if (env.IsEnvironment("Testing"))
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, true);
                    }
                }
            })
                   .UseConfiguration(configuration)
                   .UseStartup <Startup>());
        }
 public string GetSetting(string key)
 {
     return(_builder.GetSetting(key));
 }
Beispiel #28
0
        public static void Main(string[] args)
        {
            Console.WriteLine("BEGIN Main()");
            // initialize variables
            int SleeptimeWhileStarting = 0;
            int SleeptimeWhileClosing  = 0;

            string tempstring = Environment.GetEnvironmentVariable("ASPNETCORE_TOKEN");

            if (!string.IsNullOrEmpty(tempstring))
            {
                InprocessMode = false;
                tempstring    = null;
            }
            else
            {
                InprocessMode = true;
            }

            tempstring = Environment.GetEnvironmentVariable("ANCMTestStartUpDelay");
            if (!string.IsNullOrEmpty(tempstring))
            {
                SleeptimeWhileStarting         = Convert.ToInt32(tempstring);
                Startup.SleeptimeWhileStarting = SleeptimeWhileStarting;
                Console.WriteLine("SleeptimeWhileStarting: " + Startup.SleeptimeWhileStarting);
                tempstring = null;
            }

            tempstring = Environment.GetEnvironmentVariable("ANCMTestShutdownDelay");
            if (!string.IsNullOrEmpty(tempstring))
            {
                SleeptimeWhileClosing         = Convert.ToInt32(tempstring);
                Startup.SleeptimeWhileClosing = SleeptimeWhileClosing;
                Console.WriteLine("SleeptimeWhileClosing: " + Startup.SleeptimeWhileClosing);
            }

            // Build WebHost
            IWebHost        host               = null;
            IWebHostBuilder builder            = null;
            string          startUpClassString = Environment.GetEnvironmentVariable("ANCMTestStartupClassName");

            if (!string.IsNullOrEmpty(startUpClassString))
            {
                Console.WriteLine("ANCMTestStartupClassName: " + startUpClassString);
                IConfiguration config = new ConfigurationBuilder()
                                        .AddCommandLine(args)
                                        .Build();

                if (startUpClassString == "StartupHTTPS")
                {
                    // load .\testresources\testcert.pfx
                    string pfxPassword = "******";
                    if (File.Exists(@".\TestResources\testcert.pfx"))
                    {
                        _x509Certificate2 = new X509Certificate2(@".\TestResources\testcert.pfx", pfxPassword);
                    }
                    else
                    {
                        throw new Exception(@"Certificate file not found: .\TestResources\testcert.pfx of which password should " + pfxPassword);
                    }
                }
                else if (startUpClassString == "StartupCompressionCaching" || startUpClassString == "StartupNoCompressionCaching")
                {
                    if (startUpClassString == "StartupNoCompressionCaching")
                    {
                        StartupCompressionCaching.CompressionMode = false;
                    }
                    host = WebHost.CreateDefaultBuilder(args)
                           .UseConfiguration(config)
                           // BUGBUG below line is commented out because it causes 404 error with inprocess mode
                           //.UseContentRoot(Directory.GetCurrentDirectory())
                           .UseStartup <StartupCompressionCaching>()
                           .Build();
                }
                else if (startUpClassString == "StartupHelloWorld")
                {
                    host = WebHost.CreateDefaultBuilder(args)
                           .UseConfiguration(config)
                           .UseStartup <StartupHelloWorld>()
                           .Build();
                }
                else if (startUpClassString == "StartupNtlmAuthentication")
                {
                    host = WebHost.CreateDefaultBuilder(args)
                           .UseConfiguration(config)
                           .UseStartup <StartupNtlmAuthentication>()
                           .Build();
                }
                else if (startUpClassString == "StartupWithShutdownDisabled")
                {
                    builder = new WebHostBuilder()
                              .UseKestrel()
                              .ConfigureServices(services =>
                    {
                        const string PairingToken = "TOKEN";

                        string paringToken = null;
                        if (InprocessMode)
                        {
                            Console.WriteLine("Don't use IISMiddleware for inprocess mode");
                            paringToken = null;
                        }
                        else
                        {
                            Console.WriteLine("Use IISMiddleware for outofprocess mode");
                            paringToken = builder.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}");
                        }
                        services.AddSingleton <IStartupFilter>(
                            new IISSetupFilter(paringToken)
                            );
                    })
                              .UseConfiguration(config)
                              .UseStartup <Startup>();

                    host = builder.Build();
                }
                else
                {
                    throw new Exception("Invalid startup class name : " + startUpClassString);
                }
            }

            if (host == null)
            {
                host = WebHost.CreateDefaultBuilder(args)
                       .UseStartup <Startup>()
                       .Build();
            }

            // Initialize AppLifeTime events handler
            AppLifetime = (IApplicationLifetime)host.Services.GetService(typeof(IApplicationLifetime));
            AppLifetime.ApplicationStarted.Register(
                () =>
            {
                Thread.Sleep(1000);
                Console.WriteLine("AppLifetime.ApplicationStarted.Register()");
            }
                );
            AppLifetime.ApplicationStopping.Register(
                () =>
            {
                Console.WriteLine("Begin: WebSocketConnections");
                WebSocketConnections.CloseAll();
                Console.WriteLine("End: WebSocketConnections");

                Console.WriteLine("Begin: AppLifetime.ApplicationStopping.Register(), sleeping " + Startup.SleeptimeWhileClosing / 2);
                Thread.Sleep(Startup.SleeptimeWhileClosing / 2);
                Startup.SleeptimeWhileClosing = Startup.SleeptimeWhileClosing / 2;
                Console.WriteLine("End: AppLifetime.ApplicationStopping.Register()");
            }
                );
            AppLifetime.ApplicationStopped.Register(
                () =>
            {
                Console.WriteLine("Begin: AppLifetime.ApplicationStopped.Register(), sleeping " + Startup.SleeptimeWhileClosing);
                Thread.Sleep(Startup.SleeptimeWhileClosing);
                Startup.SleeptimeWhileClosing = 0;
                Console.WriteLine("End: AppLifetime.ApplicationStopped.Register()");
            }
                );

            // run
            try
            {
                Console.WriteLine("BEGIN Main::Run()");
                host.Run();
                Console.WriteLine("END Main::Run()");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception error!!! " + ex.Message);
            }

            // Sleep before finishing
            if (Startup.SleeptimeWhileClosing > 0)
            {
                Console.WriteLine("Begin: SleeptimeWhileClosing " + Startup.SleeptimeWhileClosing);
                Thread.Sleep(Startup.SleeptimeWhileClosing);
                Console.WriteLine("End: SleeptimeWhileClosing");
            }
            Console.WriteLine("END Main()");
        }
Beispiel #29
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);
        }
Beispiel #30
0
 string IWebHostBuilder.GetSetting(string key) => builder.GetSetting(key);
 public static IWebHostBuilder UseJasper(this IWebHostBuilder builder)
 {
     return(builder.UseJasper(new JasperOptionsBuilder(builder.GetSetting(WebHostDefaults.ApplicationKey))));
 }