Beispiel #1
0
        private static void BuildOptions(KestrelServerOptions options)
        {
            var certPath = Environment.GetEnvironmentVariable("WWWCERT");

            var certificate = !string.IsNullOrWhiteSpace(certPath)
                ? new X509Certificate2(certPath, Environment.GetEnvironmentVariable("WWWKEY"))
                : null;
            var environment = (IHostingEnvironment)options.ApplicationServices.GetService(typeof(IHostingEnvironment));

            if (environment.IsDevelopment())
            {
                options.Listen(IPAddress.Loopback, 5000);
                options.Listen(IPAddress.Loopback, 5001, listenOptions =>
                {
                    listenOptions.UseHttps();
                });
            }
            else
            {
                options.Listen(IPAddress.Any, 80);
                options.Listen(IPAddress.Any, 443, listenOptions =>
                {
                    listenOptions.UseHttps(certificate);
                });
            }
        }
        internal static void SetKestrelOptions(WebHostBuilderContext context, KestrelServerOptions options)
        {
            var hostConfiguration = context.Configuration.GetSection(WebApiConfiguration.SectionName)
                                    .Get <WebApiConfiguration>();

            if (hostConfiguration == null)
            {
                return;
            }

            options.Listen(IPAddress.Any, hostConfiguration.PortNumber);

            if (!hostConfiguration.HttpsPort.HasValue)
            {
                return;
            }

            var certificatePath = Path.Combine(Directory.GetCurrentDirectory(), hostConfiguration.CertificatePath);

            if (!File.Exists(certificatePath))
            {
                throw new FileNotFoundException("Файл сертификата для HTTPS не найден");
            }

            options.Listen(IPAddress.Any, hostConfiguration.HttpsPort.Value, listenOptions =>
            {
                listenOptions.UseHttps();
            });
        }
        private static void SetHost(KestrelServerOptions options, HostSettings hostSettings)
        {
            foreach (var endpoint in hostSettings.Endpoints.Values)
            {
                if (!endpoint.IsEnabled)
                {
                    continue;
                }

                var address = IPAddress.Parse(endpoint.Address);

                switch (endpoint.Scheme.ToUpperInvariant())
                {
                case Http:
                    options.Listen(address, endpoint.Port);
                    break;

                case Https:
                    options.Listen(address, endpoint.Port, opt => opt.UseHttps(GetHttpsConnectionOptions()));
                    break;

                default:
                    throw new NotImplementedException($"The scheme [{endpoint.Scheme}] is not supported.");
                }
            }
        }
Beispiel #4
0
 private static void SetHttpsAndUrls(KestrelServerOptions kestrelOptions, IWireMockMiddlewareOptions wireMockMiddlewareOptions, IEnumerable <HostUrlDetails> urlDetails)
 {
     foreach (var urlDetail in urlDetails)
     {
         if (urlDetail.IsHttps)
         {
             kestrelOptions.Listen(System.Net.IPAddress.Any, urlDetail.Port, listenOptions =>
             {
                 if (wireMockMiddlewareOptions.CustomCertificateDefined)
                 {
                     listenOptions.UseHttps(CertificateLoader.LoadCertificate(
                                                wireMockMiddlewareOptions.X509StoreName,
                                                wireMockMiddlewareOptions.X509StoreLocation,
                                                wireMockMiddlewareOptions.X509ThumbprintOrSubjectName,
                                                wireMockMiddlewareOptions.X509CertificateFilePath,
                                                wireMockMiddlewareOptions.X509CertificatePassword,
                                                urlDetail.Host)
                                            );
                 }
                 else
                 {
                     listenOptions.UseHttps();
                 }
             });
         }
         else
         {
             kestrelOptions.Listen(System.Net.IPAddress.Any, urlDetail.Port);
         }
     }
 }
Beispiel #5
0
        public static void ConfigureEndpoints(this KestrelServerOptions options)
        {
            var configuration = options.ApplicationServices.GetRequiredService <IConfiguration>();
            var environment   = options.ApplicationServices.GetRequiredService <IHostingEnvironment>();

            var hostHttp        = configuration.GetSection("HttpServer:Endpoints:Http:Host")?.Value;
            var portHostHttp    = configuration.GetSection("HttpServer:Endpoints:Http:Port")?.Value;
            var hostHttps       = configuration.GetSection("HttpServer:Endpoints:Https:Host")?.Value;
            var portHostHttps   = configuration.GetSection("HttpServer:Endpoints:Https:Port")?.Value;
            var storeName       = configuration.GetSection("HttpServer:Endpoints:Https:StoreName")?.Value;
            var storeLocation   = configuration.GetSection("HttpServer:Endpoints:Https:StoreLocation")?.Value;
            var certificateName = configuration.GetSection("HttpServer:Endpoints:Https:Name")?.Value;


            if (!string.IsNullOrEmpty(portHostHttp))
            {
                options.Listen(IPAddress.Any, Convert.ToInt32(portHostHttp));
            }

            if (!string.IsNullOrEmpty(portHostHttps))
            {
                var endpoint = new EndpointConfiguration()
                {
                    StoreLocation = storeLocation,
                    StoreName     = storeName,
                    Name          = certificateName
                };
                var certificate = LoadCertificate(endpoint, environment);
                options.Listen(IPAddress.Any, Convert.ToInt32(portHostHttps), c => c.UseHttps(certificate));
            }
        }
Beispiel #6
0
        private static void ConfigHttps(KestrelServerOptions options)
        {
            options.Listen(IPAddress.Any, 5000, listenOptions =>
            {
                //填入pfx文件路径和指定的密码
                string pfxFile = Path.Combine(Directory.GetCurrentDirectory(), "demoweb.pfx");
                listenOptions.UseHttps(pfxFile, "demo1234");
            });

            //http服务端口
            options.Listen(IPAddress.Any, 5001);
        }
Beispiel #7
0
        public void NoDelayDefaultsToTrue()
        {
            var o1 = new KestrelServerOptions();

            o1.Listen(IPAddress.Loopback, 0);
            o1.Listen(IPAddress.Loopback, 0, d =>
            {
                d.NoDelay = false;
            });

            Assert.True(o1.ListenOptions[0].NoDelay);
            Assert.False(o1.ListenOptions[1].NoDelay);
        }
Beispiel #8
0
        public static KestrelServerOptions ListenHttpAndGrpcProtocols(
            this KestrelServerOptions options,
            IConfiguration config,
            string appId)
        {
            options.Limits.MinRequestBodyDataRate = null;

            options.Listen(IPAddress.Any, config.GetHttpPort(appId));

            options.Listen(IPAddress.Any,
                           config.GetGrpcPort(appId),
                           listenOptions => { listenOptions.Protocols = HttpProtocols.Http2; });

            return(options);
        }
        public void ConfigureEndpointDefaultsAppliesToNewEndpoints()
        {
            var options = new KestrelServerOptions();

            options.ListenLocalhost(5000);

            Assert.True(options.ListenOptions[0].NoDelay);

            options.ConfigureEndpointDefaults(opt =>
            {
                opt.NoDelay = false;
            });

            options.Listen(new IPEndPoint(IPAddress.Loopback, 5000), opt =>
            {
                // ConfigureEndpointDefaults runs before this callback
                Assert.False(opt.NoDelay);
            });
            Assert.False(options.ListenOptions[1].NoDelay);

            options.ListenLocalhost(5000, opt =>
            {
                Assert.False(opt.NoDelay);
                opt.NoDelay = true; // Can be overriden
            });
            Assert.True(options.ListenOptions[2].NoDelay);


            options.ListenAnyIP(5000, opt =>
            {
                Assert.False(opt.NoDelay);
            });
            Assert.False(options.ListenOptions[3].NoDelay);
        }
        public static void UseHttps(this KestrelServerOptions options)
        {
            var config = options.ApplicationServices.GetRequiredService <IConfiguration>();
            var server = config.GetSection("ServerOptions");

            options.Listen(IPAddress.Any, 443, listenOptions => listenOptions.UseHttps(server["CertPath"]));
        }
        /// <summary>
        /// 配置Kestrel
        /// </summary>
        private static void SetHost(KestrelServerOptions options)
        {
            var address = IPAddress.Parse("0.0.0.0");

            options.Listen(address, 8880);
            options.UseSystemd();
        }
Beispiel #12
0
        public static void ConfigureServer(this KestrelServerOptions options)
        {
            string host = "localhost";

            var ipAddresses = new List <IPAddress>();

            if (host == "localhost")
            {
                ipAddresses.Add(IPAddress.Any);
                ipAddresses.Add(IPAddress.IPv6Any);
            }
            else if (IPAddress.TryParse(host, out var address))
            {
                ipAddresses.Add(address);
            }
            //else
            //{
            //	ipAddresses.Add(IPAddress.IPv6Any);
            //}

            foreach (var address in ipAddresses)
            {
                options.Listen(address, GlobalSettings.PORT,
                               listenOptions =>
                {
                    if (GlobalSettings.IS_HTTPS)
                    {
                        X509Certificate2 certificate = LoadCertificate();
                        listenOptions.UseHttps(certificate);
                    }
                });
            }
        }
    private static void ConfigureKestrel(KestrelServerOptions options, SettingsModel settings)
    {
        options.AddServerHeader    = false;
        var(httpPorts, httpsPorts) = GetPorts(settings);
        foreach (var port in httpPorts)
        {
            options.Listen(IPAddress.Any, port);
        }

        foreach (var port in httpsPorts)
        {
            options.Listen(IPAddress.Any, port,
                           listenOptions =>
                           listenOptions.UseHttps(settings.Web.PfxPath, settings.Web.PfxPassword));
        }
    }
Beispiel #14
0
        public async Task RunAsync(int port, int threadCount)
        {
            var lifetime = new ApplicationLifetime(NullLoggerFactory.Instance.CreateLogger <ApplicationLifetime>());

            Console.CancelKeyPress += (sender, e) => lifetime.StopApplication();

            var libuvOptions = new LibuvTransportOptions
            {
                ThreadCount = threadCount
            };
            var libuvTransport = new LibuvTransportFactory(
                Options.Create(libuvOptions),
                lifetime,
                NullLoggerFactory.Instance);

            var serverOptions = new KestrelServerOptions();

            serverOptions.Listen(IPAddress.Any, port);

            var server = new KestrelServer(Options.Create(serverOptions),
                                           libuvTransport,
                                           NullLoggerFactory.Instance);

            await server.StartAsync(this, CancellationToken.None);

            Console.WriteLine($"Server listening on http://*:{port} with {libuvOptions.ThreadCount} thread(s)");

            lifetime.ApplicationStopping.WaitHandle.WaitOne();

            await server.StopAsync(CancellationToken.None);
        }
Beispiel #15
0
        /// <summary>
        /// Configure Kestrel to run consistantly across the Sentinel
        /// Web and Api projects.
        /// </summary>
        /// <param name="options"></param>
        /// <param name="hostingEnvironment">Hosting Environment Properites</param>
        /// <param name="configuration">Configuration Properties</param>
        /// <param name="localPort">Choose the port for this service to function on</param>
        public static void Configure(KestrelServerOptions options,
                                     IHostingEnvironment hostingEnvironment,
                                     IConfiguration configuration,
                                     int localPort)
        {
            try
            {
                Log.Information("Setting Kestrel Server Options");

                // var sslCertificate = SOME CONFIGURATION TO GET CERTIFICATES FOR HTTPS

                //var port = hostingEnvironment.IsEnvironment(EnvironmentTypes.Local)
                //    ? localPort
                //    : 443;

                options.Listen(IPAddress.Any, localPort, listenOptions =>
                {
                    listenOptions.NoDelay = true;
                    //listenOptions.UseHttps(sslCertificate);
                });
            }
            catch (Exception exception)
            {
                Log.Fatal(exception, "Host terminated unexpectedly! -- {Message}", exception.Message);
            }
        }
        public void ConfigureEndpointDefaultsAppliesToNewEndpoints()
        {
            var options = new KestrelServerOptions();

            options.ListenLocalhost(5000);

            Assert.Equal(HttpProtocols.Http1AndHttp2, options.CodeBackedListenOptions[0].Protocols);

            options.ConfigureEndpointDefaults(opt =>
            {
                opt.Protocols = HttpProtocols.Http1;
            });

            options.Listen(new IPEndPoint(IPAddress.Loopback, 5000), opt =>
            {
                // ConfigureEndpointDefaults runs before this callback
                Assert.Equal(HttpProtocols.Http1, opt.Protocols);
            });
            Assert.Equal(HttpProtocols.Http1, options.CodeBackedListenOptions[1].Protocols);

            options.ListenLocalhost(5000, opt =>
            {
                Assert.Equal(HttpProtocols.Http1, opt.Protocols);
                opt.Protocols = HttpProtocols.Http2; // Can be overriden
            });
            Assert.Equal(HttpProtocols.Http2, options.CodeBackedListenOptions[2].Protocols);

            options.ListenAnyIP(5000, opt =>
            {
                opt.Protocols = HttpProtocols.Http2;
            });
            Assert.Equal(HttpProtocols.Http2, options.CodeBackedListenOptions[3].Protocols);
        }
Beispiel #17
0
        static async Task Main(string[] args)
        {
            var socketTransportOptions = new SocketTransportOptions();
            var socketTransportFactory = new SocketTransportFactory(Options.Create(socketTransportOptions), NullLoggerFactory.Instance);
            var kestrelServerOptions   = new KestrelServerOptions();

            kestrelServerOptions.Listen(IPAddress.Any, 8080);
            kestrelServerOptions.AddServerHeader = false;

            using var kestrelServer = new KestrelServer(Options.Create(kestrelServerOptions), socketTransportFactory, NullLoggerFactory.Instance);

            await kestrelServer.StartAsync(new HttpApplication(), CancellationToken.None);

            Console.WriteLine("Listening on:");

            foreach (var address in kestrelServer.Features.Get <IServerAddressesFeature>().Addresses)
            {
                Console.WriteLine(" - " + address);
            }

            Console.WriteLine("Process CTRL+C to quit");
            var wh = new ManualResetEventSlim();

            Console.CancelKeyPress += (sender, e) => wh.Set();
            wh.Wait();
        }
Beispiel #18
0
        private static void Listen(KestrelServerOptions options, IConfigurationRoot config, string url)
        {
            var urlPrefix = UrlPrefix.Create(url);
            var endpoint  = CreateIPEndPoint(urlPrefix);

            options.Listen(endpoint, listenOptions =>
            {
                var connectionFilter = GetConnectionFilter(config);
                if (connectionFilter != null)
                {
                    listenOptions.ConnectionAdapters.Add(connectionFilter);
                }

#if !NETCOREAPP2_0 && !NETCOREAPP2_1
                if (Protocol.Equals("h2", StringComparison.OrdinalIgnoreCase))
                {
                    listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                }
                else if (Protocol.Equals("h2c", StringComparison.OrdinalIgnoreCase))
                {
                    listenOptions.Protocols = HttpProtocols.Http2;
                }
#endif

                if (urlPrefix.IsHttps)
                {
                    listenOptions.UseHttps("testCert.pfx", "testPassword");
                }
            });
        }
 public static void UseSslIfFileExists(this KestrelServerOptions options, int port, string pfxFilePath, string password = null)
 {
     if (File.Exists(pfxFilePath))
     {
         options.Listen(IPAddress.Any, port, listen => listen.UseHttps(pfxFilePath, password));
     }
 }
Beispiel #20
0
        private static void ipConfig(KestrelServerOptions o)
        {
            var portStr = CmdHelper.QueryParameter("-p", "8080");

            if (!int.TryParse(portStr, out int port))
            {
                port = 9001;
            }
            var ip = CmdHelper.QueryParameter("-ip", "localhost");

            Console.WriteLine(ip);
            if (ip.ToLower() == "any")
            {
                Console.WriteLine("ListenAnyIP");
                o.ListenAnyIP(port);
            }
            else if (ip == "127.0.0.1" || ip.ToLower() == "localhost")
            {
                Console.WriteLine("ListenLocalhost");
                o.ListenLocalhost(port);
            }
            else
            {
                Console.WriteLine("Listen");
                o.Listen(System.Net.IPAddress.Parse(ip), port);
            }
        }
        /// <summary>
        /// 配置Kestrel
        /// </summary>
        private static void SetHost(KestrelServerOptions options)
        {
            var address = IPAddress.Parse("0.0.0.0");

            options.Listen(address, ServiceConfigInfo.HttpPort);
            options.UseSystemd();
        }
Beispiel #22
0
 private static void ConfigKestrel(KestrelServerOptions opts)
 {
     opts.Listen(IPAddress.Parse("192.168.10.82"), 10000, listenOptions =>
     {
         //填入之前iis中生成的pfx文件路径和指定的密码            
         listenOptions.UseHttps(@"F:\Git\Snail.Release\Snail.Release\wwwroot\crt\webrtc1.pfx", "chennanfei");
     });
 }
Beispiel #23
0
        private static void ConfigureKestrel(WebHostBuilderContext context, KestrelServerOptions serverOptions)
        {
            Log.Debug("ConfigureKestrel");
            var config = context.Configuration.Get <StartUpConfiguration>();

            config.SetDefaultSettings();

            var listenIp = IPAddress.Parse(config.ListeningIP);

            if (config.HttpPort.HasValue && config.HttpPort.Value != 0)
            {
                serverOptions.Listen(listenIp, config.HttpPort.Value, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                });
            }

            if (config.HttpsPort.HasValue && config.HttpsPort.Value != 0)
            {
                var certPath = PathHelper.GetFullPath(config.HttpsCertPath);
                Log.Debug(certPath);
                serverOptions.Listen(listenIp, config.HttpsPort.Value, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                    listenOptions.UseHttps(PathHelper.GetFullPath(config.HttpsCertPath), config.HttpsCertPassword);
                });
            }

            var adminListenIp = IPAddress.Parse(config.AdminSettings.ListeningIP);

            serverOptions.Listen(adminListenIp, config.AdminSettings.HttpsPort, options =>
            {
                options.Protocols = HttpProtocols.Http1AndHttp2;
                options.UseHttps(PathHelper.GetFullPath(config.AdminSettings.HttpsCertPath),
                                 config.AdminSettings.HttpsCertPassword);
            });

            var idpListenIp = IPAddress.Parse(config.IdpSettings.ListeningIP);

            serverOptions.Listen(idpListenIp, config.IdpSettings.HttpsPort, options =>
            {
                options.Protocols = HttpProtocols.Http1AndHttp2;

                options.UseHttps(PathHelper.GetFullPath(config.IdpSettings.HttpsCertPath), config.IdpSettings.HttpsCertPassword);
            });
        }
        /// <summary>
        /// Add the certificates for the https endpoints
        /// </summary>
        /// <param name="options">Input options</param>
        public static void ConfigureEndpoints(this KestrelServerOptions options)
        {
            var environment = options.ApplicationServices.GetRequiredService <IHostingEnvironment>();

            var endpoints = new List <EndpointConfiguration>
            {
                new EndpointConfiguration
                {
                    Host          = "localhost",
                    Port          = 5001,
                    Scheme        = "https",
                    StoreName     = "My",
                    StoreLocation = "CurrentUser",
                },
                new EndpointConfiguration
                {
                    Host   = "localhost",
                    Port   = 5000,
                    Scheme = "http",
                },
            };

            foreach (var endpoint in endpoints)
            {
                var config = endpoint;
                var port   = config.Port ?? (config.Scheme == "https" ? 443 : 80);

                var ipAddresses = new List <IPAddress>();
                if (config.Host == "localhost")
                {
                    ipAddresses.Add(IPAddress.IPv6Loopback);
                    ipAddresses.Add(IPAddress.Loopback);
                }
                else if (IPAddress.TryParse(config.Host, out var address))
                {
                    ipAddresses.Add(address);
                }
                else
                {
                    ipAddresses.Add(IPAddress.IPv6Any);
                }

                foreach (var address in ipAddresses)
                {
                    options.Listen(
                        address,
                        port,
                        listenOptions =>
                    {
                        if (config.Scheme == "https")
                        {
                            var certificate = LoadCertificate(config, environment);
                            listenOptions.UseHttps(certificate);
                        }
                    });
                }
            }
        }
        public static void ConfigureEndpoints(this KestrelServerOptions options)
        {
            if (options is null)
            {
                return;
            }

            var configuration = options.ApplicationServices.GetRequiredService <IConfiguration>();
            var environment   = options.ApplicationServices.GetRequiredService <IHostEnvironment>();

            var endpoints = configuration.GetSection("HttpServer:Endpoints")
                            .GetChildren()
                            .ToDictionary(
                section => section.Key,
                section =>
            {
                var endpoint = new EndpointConfiguration();
                section.Bind(endpoint);
                return(endpoint);
            }
                );

            foreach (var endpoint in endpoints)
            {
                var config = endpoint.Value;
                var port   = config.Port ?? (config.Scheme == "https" ? 443 : 80);

                var ipAddresses = new List <IPAddress>();
                if (config.Host == "localhost")
                {
                    ipAddresses.Add(IPAddress.IPv6Loopback);
                    ipAddresses.Add(IPAddress.Loopback);
                }
                else if (IPAddress.TryParse(config.Host, out var address))
                {
                    ipAddresses.Add(address);
                }
                else
                {
                    ipAddresses.Add(IPAddress.IPv6Any);
                }

                foreach (var address in ipAddresses)
                {
                    options.Listen(
                        address,
                        port,
                        listenOptions =>
                    {
                        if (config.Scheme == "https")
                        {
                            var certificate = LoadCertificate(config);
                            listenOptions.UseHttps(certificate);
                        }
                    });
                }
            }
        }
Beispiel #26
0
        /// <summary>
        /// 配置Kestrel
        /// </summary>
        private static void SetHost(KestrelServerOptions options)
        {
            var address = IPAddress.Parse("0.0.0.0");

            options.Listen(address, ServiceConfigInfo.HttpPort);
            options.UseSystemd();
            options.Limits.KeepAliveTimeout      = TimeSpan.FromSeconds(30);
            options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30);
        }
Beispiel #27
0
        private static void SetKestrelConfiguration(KestrelServerOptions options, IConfiguration configuration)
        {
            var portsConfig = configuration.GetSection("Ports");
            int httpPort    = portsConfig.GetValue <int>("Http");

            options.Listen(IPAddress.Any, httpPort, listenOptions =>
            {
                listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
            });
        }
Beispiel #28
0
 private static void ConfigureKestrel(KestrelServerOptions options)
 {
     options.Listen(
         IPAddress.Any,
         31337,
         builder =>
     {
         // TODO
     });
 }
Beispiel #29
0
        protected override void ConfigureKestrel(KestrelServerOptions options)
        {
            options.Listen(EndPoint, listneOptions =>
            {
                byte[] pfx  = ResourceManager.GetResourceBytes("server.pfx");
                var pfxCert = new X509Certificate2(pfx, "minime");

                listneOptions.UseHttps(pfxCert);
            });
        }
        protected override void ConfigureKestrel(KestrelServerOptions options, string hostname)
        {
            var certificate = _certificateFactory.GenerateCertificate(hostname);

            options.Listen(IPAddress.Loopback, 0, listener => listener.UseHttps(https =>
            {
                https.ServerCertificate     = certificate;
                https.ClientCertificateMode = ClientCertificateMode.AllowCertificate;
                https.AllowAnyClientCertificate();
            }));
        }