public static void Main(string[] args)
        {
            FakeDiagnosticListenerObserver diagnosticListenerObserver = null;

            if (UseActivityToPropagateCv)
            {
                diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { });

                // Enable three extension points to enable Correlation Vector tracking along with the
                // Activity and Request-Id
                //
                Activity.RegisterActivityExtension <CorrelationVectorExtension>();
                HttpClientHandler.RegisterCorrelationPropagationDelegate(
                    CorrelationVectorPropagationDelegates.FromCurrentActivityExtension);
                HostingApplication.RegisterCorrelationConsumer(new CorrelationVectorConsumer());
            }
            else
            {
                HttpClientHandler.RegisterCorrelationPropagationDelegate(
                    CorrelationVectorPropagationDelegates.FromHttpRequestMessageProperty);
                HostingApplication.RegisterCorrelationConsumer(new CorrelationVectorHttpContextConsumer());
            }

            // Issue a request to the controller to simulate a caller
            //
            Timer executeCallTimer = new Timer(IssueRequest, state: null, dueTime: 1500, period: Timeout.Infinite);

            using (diagnosticListenerObserver == null ?
                   null:
                   DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
            {
                CreateWebHostBuilder(args).Build().Run();
            }
        }
Esempio n. 2
0
        public static async Task Main(string[] args)
        {
            shutdown = new ManualResetEventSlim();
            Console.CancelKeyPress += Console_CancelKeyPress;

            var options = new KestrelServerOptions();

            options.ListenAnyIP(5000, c =>
            {
                c.UseHttpApplication <Application>();
            });

            var server = new KestrelServer(
                Options.Create(options),
                new SocketTransportFactory(
                    Options.Create(new SocketTransportOptions()),
                    NullLoggerFactory.Instance),
                NullLoggerFactory.Instance);

            var application = new HostingApplication((context) => Task.CompletedTask, new DefaultHttpContextFactory(new ServiceProvider()));
            await server.StartAsync(application, CancellationToken.None);

            Console.WriteLine("Application started.");
            shutdown.Wait();

            Console.WriteLine("Shutting down...");
            server.Dispose();
            await server.StopAsync(CancellationToken.None);
        }
Esempio n. 3
0
        /// <summary>
        /// Starts running a new KafkaBus host.
        /// </summary>
        /// <param name="app">The Application builder</param>
        /// <param name="subscriber">The KafkaBus subscriber</param>
        /// <param name="skipKafkaBusServerCheck">Set to true to run the host even if the application server is the KafkaBus.AspNet server</param>
        public static void RunKafkaBusHost(this IApplicationBuilder app, IKafkaBusSubscriber subscriber, bool skipKafkaBusServerCheck)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (subscriber == null)
            {
                throw new ArgumentNullException("subscriber");
            }

            if (!skipKafkaBusServerCheck && Server.InstanceCount > 0)
            {
                //The application is running KafkaBusServer, so exit
                return;
            }

            var appFunc = app.Build();

            var _loggerFactory     = app.ApplicationServices.GetRequiredService <ILoggerFactory>();
            var diagnosticSource   = app.ApplicationServices.GetRequiredService <DiagnosticSource>();
            var httpContextFactory = app.ApplicationServices.GetRequiredService <IHttpContextFactory>();

            //TODO: Work on counting instances (all hosts + server)  and adding the count to the logger name e.g KafkaBus.AspNet (2), consider including the typename as well.
            var application = new HostingApplication(appFunc, _loggerFactory.CreateLogger(typeof(Server).FullName), diagnosticSource, httpContextFactory);
            var server      = app.ApplicationServices.GetRequiredService <Server>();

            server.Start(application, subscriber);
        }
Esempio n. 4
0
        public virtual async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            HostingEventSource.Log.HostStart();
            _logger = _applicationServices.GetRequiredService <ILogger <WebHost> >();

            Initialize();

            _applicationLifetime   = _applicationServices.GetRequiredService <IApplicationLifetime>() as ApplicationLifetime;
            _hostedServiceExecutor = _applicationServices.GetRequiredService <HostedServiceExecutor>();
            var diagnosticSource   = _applicationServices.GetRequiredService <DiagnosticListener>();
            var httpContextFactory = _applicationServices.GetRequiredService <IHttpContextFactory>();
            var hostingApp         = new HostingApplication(_application, _logger, diagnosticSource, httpContextFactory);
            await Server.StartAsync(hostingApp, cancellationToken).ConfigureAwait(false);

            // Fire IApplicationLifetime.Started
            _applicationLifetime?.NotifyStarted();

            // Fire IHostedService.Start
            await _hostedServiceExecutor.StartAsync(cancellationToken).ConfigureAwait(false);

            // Log the fact that we did load hosting startup assemblies.
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                foreach (var assembly in _options.HostingStartupAssemblies)
                {
                    _logger.LogDebug("Loaded hosting startup assembly {assemblyName}", assembly);
                }
            }
        }
Esempio n. 5
0
        public virtual async Task StartAsync(CancellationToken cancellationToken = default)
        {
            HostingEventSource.Log.HostStart();
            _logger.Starting();

            var application = BuildApplication();

            var diagnosticSource   = Services.GetRequiredService <DiagnosticListener>();
            var httpContextFactory = Services.GetRequiredService <IHttpContextFactory>();
            var hostingApp         = new HostingApplication(application, _logger, diagnosticSource, httpContextFactory);

            await Server.StartAsync(hostingApp, cancellationToken).ConfigureAwait(false);

            // Fire IApplicationLifetime.Started
            _applicationLifetime?.NotifyStarted();

            _logger.Started();

            // Log the fact that we did load hosting startup assemblies.
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                foreach (var assembly in _options.GetFinalHostingStartupAssemblies())
                {
                    _logger.LogDebug("Loaded hosting startup assembly {assemblyName}", assembly);
                }
            }

            if (_hostingStartupErrors != null)
            {
                foreach (var exception in _hostingStartupErrors.InnerExceptions)
                {
                    _logger.HostingStartupAssemblyError(exception);
                }
            }
        }
Esempio n. 6
0
        private async Task startAspNetCoreServer()
        {
            if (!Registry.HttpRoutes.Enabled || Registry.BootstrappedWithinAspNetCore)
            {
                return;
            }


            HostingEventSource.Log.HostStart();

            _logger = Get <ILoggerFactory>().CreateLogger("Jasper");

            _applicationLifetime = TypeExtensions.As <ApplicationLifetime>(Container.GetInstance <IApplicationLifetime>());

            var httpContextFactory = Container.QuickBuild <HttpContextFactory>();

            var hostingApp = new HostingApplication(
                RequestDelegate,
                _logger,
                Container.GetInstance <DiagnosticListener>(), // See if this can be passed in directly
                httpContextFactory);

            await _server.StartAsync(hostingApp, Settings.Cancellation);

            // Fire IApplicationLifetime.Started
            _applicationLifetime?.NotifyStarted();
        }
Esempio n. 7
0
        /// <summary>
        /// Starts running a new RestBus host.
        /// </summary>
        /// <param name="app">The Application builder</param>
        /// <param name="subscriber">The RestBus subscriber</param>
        /// <param name="skipRestBusServerCheck">Set to true to run the host even if the application server is the RestBus.AspNet server</param>
        public static void RunRestBusHost(this IApplicationBuilder app, IRestBusSubscriber subscriber, bool skipRestBusServerCheck)
        {
            if (app == null) throw new ArgumentNullException("app");
            if (subscriber == null) throw new ArgumentNullException("subscriber");

            if (!skipRestBusServerCheck && 
                app.ApplicationServices.GetRequiredService<IHostingEnvironment>().Configuration[Server.Server.ConfigServerArgumentName] == Server.Server.ConfigServerAssembly)
            {
                //The application is running RestBusServer, so exit
                return;
            }

            var appFunc = app.Build();

            var _loggerFactory = app.ApplicationServices.GetRequiredService<ILoggerFactory>();
            var diagnosticSource = app.ApplicationServices.GetRequiredService<DiagnosticSource>();
            var httpContextFactory = app.ApplicationServices.GetRequiredService<IHttpContextFactory>();

            //TODO: Work on counting instances (all hosts + server)  and adding the count to the logger name e.g RestBus.AspNet (2), consider including the typename as well.
            var application = new HostingApplication(appFunc, _loggerFactory.CreateLogger(Server.Server.ConfigServerAssembly), diagnosticSource, httpContextFactory);

            var host = new RestBusHost<HostingApplication.Context>(subscriber, application);

            //Register host for disposal
            var appLifeTime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();

            appLifeTime.ApplicationStopping.Register(() => host.Dispose()); //TODO: Make ApplicationStopping event stop dequeueing items (StopPollingQueue)
            appLifeTime.ApplicationStopped.Register(() => host.Dispose());

            //Start host
            host.Start();
        }
        public Task StartAsync(HostingApplication hostingApplication, CancellationToken cancellationToken)
        {
            _routerSocket = new RouterSocket();
            _routerSocket.Bind($"tcp://{_hostingOptions.Host}");
            _routerSocket.ReceiveReady += RouterSocket_ReceiveReady;
            _dealerSocket = new DealerSocket();
            _dealerSocket.Bind(INPROC_SERVER_URL);
            _dealerSocket.ReceiveReady += DealerSocket_ReceiveReady;

            _poller = new NetMQPoller {
                _routerSocket, _dealerSocket
            };
            _poller.RunAsync();
            _workerPoller = new NetMQPoller();
            async void OnReceiveReady(object sender, NetMQSocketEventArgs args)
            {
                NetMQMessage receiveMessage = args.Socket.ReceiveMultipartMessage();
                string       address        = receiveMessage.Pop().ConvertToString();
                string       content        = receiveMessage.Last().ConvertToString(Encoding.UTF8);
                OwinContext  owinContext    = null;
                long         startTimestamp = Stopwatch.GetTimestamp();

                _logger.LogInformation($"Request starting tcp://{_hostingOptions.Host} {content}");
                owinContext = hostingApplication.CreateContext(content);
                try
                {
                    await hostingApplication.ProcessRequestAsync(owinContext);
                }
                catch (Exception ex)
                {
                    owinContext.Response.Error(ex.Message);
                    throw;
                }
                finally
                {
                    string sendContent = _serializer.Serialize(owinContext.Response);
                    _logger.LogInformation($"Request finished in {new TimeSpan((long)(TimestampToTicks * (Stopwatch.GetTimestamp() - startTimestamp))).TotalMilliseconds}ms {sendContent}");
                    NetMQMessage sendMessage = new NetMQMessage();
                    sendMessage.Append(address);
                    sendMessage.AppendEmptyFrame();
                    sendMessage.Append(sendContent, Encoding.UTF8);
                    args.Socket.SendMultipartMessage(sendMessage);
                    hostingApplication.DisponseContext(owinContext);
                }
            }

            foreach (var item in Enumerable.Range(0, _hostingOptions.ProcessCount))
            {
                NetMQSocket process = new DealerSocket();
                process.Connect(INPROC_SERVER_URL);
                process.ReceiveReady += OnReceiveReady;
                _workerPoller.Add(process);
            }

            _workerPoller.RunAsync();
            return(Task.CompletedTask);
        }
        public void DisposeContextDoesNotThrowWhenContextScopeIsNull()
        {
            // Arrange
            var httpContextFactory = new HttpContextFactory(new DefaultObjectPoolProvider(), Options.Create(new FormOptions()), new HttpContextAccessor());
            var hostingApplication = new HostingApplication(ctx => Task.FromResult(0), new NullScopeLogger(), new NoopDiagnosticSource(), httpContextFactory);
            var context            = hostingApplication.CreateContext(new FeatureCollection());

            // Act/Assert
            hostingApplication.DisposeContext(context, null);
        }
Esempio n. 10
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            Server.Features.Get <IServerAddressesFeature>()?.Addresses.Add("http://localhost:5000");

            var builder = new ApplicationBuilder(Services, Server.Features);

            Options.ConfigureApp(HostBuilderContext, builder);
            var app = builder.Build();

            var httpApp = new HostingApplication(app, Logger, DiagnosticListener, HttpContextFactory);

            return(Server.StartAsync(httpApp, cancellationToken));
        }
Esempio n. 11
0
        public void GlobalSetup()
        {
            _serviceProvider = new ServiceCollection()
                               .AddLogging()
                               .AddOpenTracingCoreServices(builder =>
            {
                builder.AddAspNetCore();
                builder.AddBenchmarkTracer(Mode);
            })
                               .BuildServiceProvider();

            var diagnosticManager = _serviceProvider.GetRequiredService <DiagnosticManager>();

            diagnosticManager.Start();

            // Request

            _httpContext = new DefaultHttpContext();
            var request = _httpContext.Request;

            Uri requestUri = new Uri("http://www.example.com/foo");

            request.Protocol = "HTTP/1.1";
            request.Method   = HttpMethods.Get;
            request.Scheme   = requestUri.Scheme;
            request.Host     = HostString.FromUriComponent(requestUri);
            if (requestUri.IsDefaultPort)
            {
                request.Host = new HostString(request.Host.Host);
            }
            request.PathBase    = PathString.Empty;
            request.Path        = PathString.FromUriComponent(requestUri);
            request.QueryString = QueryString.FromUriComponent(requestUri);

            // Hosting Application

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");

            _features = new FeatureCollection();
            _features.Set <IHttpRequestFeature>(new HttpRequestFeature());

            var httpContextFactory = Substitute.For <IHttpContextFactory>();

            httpContextFactory.Create(_features).Returns(_httpContext);

            _hostingApplication = new HostingApplication(
                ctx => Task.FromResult(0),
                _serviceProvider.GetRequiredService <ILogger <RequestDiagnosticsBenchmark> >(),
                diagnosticSource,
                httpContextFactory);
        }
        public Task StartAsync(HostingApplication hostingApplication, CancellationToken cancellationToken)
        {
            _routerSocket = new RouterSocket();
            _routerSocket.Bind($"tcp://{_hostingOptions.Host}");
            _routerSocket.ReceiveReady += RouterSocket_ReceiveReady;
            _dealerSocket = new DealerSocket();
            _dealerSocket.Bind(INPROC_SERVER_URL);
            _dealerSocket.ReceiveReady += DealerSocket_ReceiveReady;
            _poller = new NetMQPoller {
                _routerSocket, _dealerSocket
            };
            _poller.RunAsync();

            return(Task.CompletedTask);
        }
Esempio n. 13
0
        public static void Main(string[] args)
        {
            // Enable three extension points to enable Correlation Vector tracking along with the
            // Activity and Request-Id
            Activity.RegisterActivityExtension <CorrelationVectorExtension>();
            HttpClientHandler.RegisterCorrelationPropagationDelegate(
                CorrelationVectorPropagationDelegates.FromCurrentActivityExtension);
            HostingApplication.RegisterCorrelationConsumer(new CorrelationVectorActivityExtensionConsumer());

            // Issue a request to the controller to simulate a caller
            //
            Timer executeCallTimer = new Timer(IssueRequest, state: null, dueTime: 1500, period: Timeout.Infinite);

            CreateWebHostBuilder(args).Build().Run();
        }
Esempio n. 14
0
        public HostingTest(ITestOutputHelper output)
        {
            _tracer = new MockTracer();

            var aspNetCoreOptions = new AspNetCoreDiagnosticOptions();

            _options = aspNetCoreOptions.Hosting;

            _serviceProvider = new ServiceCollection()
                               .AddLogging(logging =>
            {
                logging.AddXunit(output);
                logging.AddFilter("OpenTracing", LogLevel.Trace);
            })
                               .AddOpenTracingCoreServices(builder =>
            {
                builder.AddAspNetCore();

                builder.Services.AddSingleton <ITracer>(_tracer);
                builder.Services.AddSingleton(Options.Create(aspNetCoreOptions));
            })
                               .BuildServiceProvider();

            _diagnosticManager = _serviceProvider.GetRequiredService <DiagnosticManager>();
            _diagnosticManager.Start();

            // Request

            _httpContext = new DefaultHttpContext();
            SetRequest();

            // Hosting Application

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");

            _features = new FeatureCollection();
            _features.Set <IHttpRequestFeature>(new HttpRequestFeature());

            var httpContextFactory = Substitute.For <IHttpContextFactory>();

            httpContextFactory.Create(_features).Returns(_httpContext);

            _hostingApplication = new HostingApplication(
                ctx => Task.FromResult(0),
                _serviceProvider.GetRequiredService <ILogger <HostingTest> >(),
                diagnosticSource,
                httpContextFactory);
        }
Esempio n. 15
0
    public async Task StartAsync(CancellationToken cancellationToken = default)
    {
        Debug.Assert(_applicationServices != null, "Initialize must be called first.");

        HostingEventSource.Log.HostStart();
        _logger = _applicationServices.GetRequiredService <ILoggerFactory>().CreateLogger("Microsoft.AspNetCore.Hosting.Diagnostics");
        Log.Starting(_logger);

        var application = BuildApplication();

        _applicationLifetime   = _applicationServices.GetRequiredService <ApplicationLifetime>();
        _hostedServiceExecutor = _applicationServices.GetRequiredService <HostedServiceExecutor>();

        // Fire IHostedService.Start
        await _hostedServiceExecutor.StartAsync(cancellationToken).ConfigureAwait(false);

        var diagnosticSource   = _applicationServices.GetRequiredService <DiagnosticListener>();
        var activitySource     = _applicationServices.GetRequiredService <ActivitySource>();
        var propagator         = _applicationServices.GetRequiredService <DistributedContextPropagator>();
        var httpContextFactory = _applicationServices.GetRequiredService <IHttpContextFactory>();
        var hostingApp         = new HostingApplication(application, _logger, diagnosticSource, activitySource, propagator, httpContextFactory);
        await Server.StartAsync(hostingApp, cancellationToken).ConfigureAwait(false);

        _startedServer = true;

        // Fire IApplicationLifetime.Started
        _applicationLifetime?.NotifyStarted();

        Log.Started(_logger);

        // Log the fact that we did load hosting startup assemblies.
        if (_logger.IsEnabled(LogLevel.Debug))
        {
            foreach (var assembly in _options.GetFinalHostingStartupAssemblies())
            {
                Log.StartupAssemblyLoaded(_logger, assembly);
            }
        }

        if (_hostingStartupErrors != null)
        {
            foreach (var exception in _hostingStartupErrors.InnerExceptions)
            {
                _logger.HostingStartupAssemblyError(exception);
            }
        }
    }
Esempio n. 16
0
        private static HostingApplication CreateApplication(out FeatureCollection features,
                                                            DiagnosticListener diagnosticSource = null, ILogger logger = null)
        {
            var httpContextFactory = new Mock <IHttpContextFactory>();

            features = new FeatureCollection();
            features.Set <IHttpRequestFeature>(new HttpRequestFeature());
            httpContextFactory.Setup(s => s.Create(It.IsAny <IFeatureCollection>())).Returns(new DefaultHttpContext(features));
            httpContextFactory.Setup(s => s.Dispose(It.IsAny <HttpContext>()));

            var hostingApplication = new HostingApplication(
                ctx => Task.CompletedTask,
                logger ?? new NullScopeLogger(),
                diagnosticSource ?? new NoopDiagnosticSource(),
                httpContextFactory.Object);

            return(hostingApplication);
        }
        private static HostingApplication CreateApplication(IHttpContextFactory httpContextFactory = null, bool useHttpContextAccessor = false)
        {
            var services = new ServiceCollection();

            services.AddOptions();
            if (useHttpContextAccessor)
            {
                services.AddHttpContextAccessor();
            }

            httpContextFactory ??= new DefaultHttpContextFactory(services.BuildServiceProvider());

            var hostingApplication = new HostingApplication(
                ctx => Task.CompletedTask,
                NullLogger.Instance,
                new DiagnosticListener("Microsoft.AspNetCore"),
                httpContextFactory);

            return(hostingApplication);
        }
 public async Task StartAsync(HostingApplication hostingApplication, CancellationToken cancellationToken)
 {
     _webHost = new WebHostBuilder()
                .UseKestrel()
                .UseUrls($"http://{_hostingOptions.Host}")
                .UseConfiguration(_configuration)
                .ConfigureLogging(builder =>
     {
         foreach (var provider in _loggerProviders)
         {
             builder.AddProvider(provider);
         }
     })
                .Configure(app =>
     {
         app.Use(IgnoreFavicon());
         app.Use(RequestDispatch(hostingApplication, cancellationToken));
     })
                .Build();
     await _webHost.StartAsync(cancellationToken);
 }
Esempio n. 19
0
        /// <summary>
        /// Starts running a new RestBus host.
        /// </summary>
        /// <param name="app">The Application builder</param>
        /// <param name="subscriber">The RestBus subscriber</param>
        /// <param name="skipRestBusServerCheck">Set to true to run the host even if the application server is the RestBus.AspNet server</param>
        public static void RunRestBusHost(this IApplicationBuilder app, IRestBusSubscriber subscriber, bool skipRestBusServerCheck)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (subscriber == null)
            {
                throw new ArgumentNullException("subscriber");
            }

            if (!skipRestBusServerCheck &&
                app.ApplicationServices.GetRequiredService <IHostingEnvironment>().Configuration[Server.Server.ConfigServerArgumentName] == Server.Server.ConfigServerAssembly)
            {
                //The application is running RestBusServer, so exit
                return;
            }

            var appFunc = app.Build();

            var _loggerFactory     = app.ApplicationServices.GetRequiredService <ILoggerFactory>();
            var diagnosticSource   = app.ApplicationServices.GetRequiredService <DiagnosticSource>();
            var httpContextFactory = app.ApplicationServices.GetRequiredService <IHttpContextFactory>();

            //TODO: Work on counting instances (all hosts + server)  and adding the count to the logger name e.g RestBus.AspNet (2), consider including the typename as well.
            var application = new HostingApplication(appFunc, _loggerFactory.CreateLogger(Server.Server.ConfigServerAssembly), diagnosticSource, httpContextFactory);

            var host = new RestBusHost <HostingApplication.Context>(subscriber, application);

            //Register host for disposal
            var appLifeTime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>();

            appLifeTime.ApplicationStopping.Register(() => host.Dispose()); //TODO: Make ApplicationStopping event stop dequeueing items (StopPollingQueue)
            appLifeTime.ApplicationStopped.Register(() => host.Dispose());

            //Start host
            host.Start();
        }
Esempio n. 20
0
    private static HostingApplication CreateApplication(out FeatureCollection features,
                                                        DiagnosticListener diagnosticListener = null, ActivitySource activitySource = null, ILogger logger = null, Action <DefaultHttpContext> configure = null)
    {
        var httpContextFactory = new Mock <IHttpContextFactory>();

        features = new FeatureCollection();
        features.Set <IHttpRequestFeature>(new HttpRequestFeature());
        var context = new DefaultHttpContext(features);

        configure?.Invoke(context);
        httpContextFactory.Setup(s => s.Create(It.IsAny <IFeatureCollection>())).Returns(context);
        httpContextFactory.Setup(s => s.Dispose(It.IsAny <HttpContext>()));

        var hostingApplication = new HostingApplication(
            ctx => Task.CompletedTask,
            logger ?? new NullScopeLogger(),
            diagnosticListener ?? new NoopDiagnosticListener(),
            activitySource ?? new ActivitySource("Microsoft.AspNetCore"),
            DistributedContextPropagator.CreateDefaultPropagator(),
            httpContextFactory.Object);

        return(hostingApplication);
    }
        public async Task Start()
        {
            IHttpApplication <HostingApplication.Context> app;

            try
            {
                if (_handler == null)
                {
                    throw new Exception("Missing Handler - Call SetHandler()");
                }

                ILoggerFactory loggerFactory = new LoggerFactory();
                loggerFactory.AddProvider(new KestrelLoggerProvider());
                var services = new ServiceCollection();
                services.AddSingleton(loggerFactory);
                services.AddLogging();

                var serviceProvider      = GetProviderFromFactory(services);
                var kestrelServerOptions = Options.Create(new KestrelServerOptions());
                kestrelServerOptions.Value.ApplicationServices = serviceProvider;

                foreach (uint httpPort in _setting.HttpPorts)
                {
                    kestrelServerOptions.Value.ListenAnyIP((int)httpPort);
                }

                if (_setting.HttpsEnabled)
                {
                    kestrelServerOptions.Value.ListenAnyIP(_setting.HttpsPort,
                                                           listenOptions =>
                    {
                        var cert = new X509Certificate2(_setting.HttpsCertPath,
                                                        _setting.HttpsCertPw);
                        listenOptions.UseHttps(new HttpsConnectionAdapterOptions
                        {
                            ServerCertificate = cert
                                                //  SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls
                        });
                    });
                }
                // kestrelServerOptions.Value.ListenAnyIP(_setting.WebSetting.HttpsPort);

                kestrelServerOptions.Value.AddServerHeader = false;

                var socketTransportOptions = Options.Create(new SocketTransportOptions());
                _applicationLifetime = new ApplicationLifetime(
                    loggerFactory.CreateLogger <ApplicationLifetime>()
                    );
                ITransportFactory transportFactory = new SocketTransportFactory(
                    socketTransportOptions, _applicationLifetime, loggerFactory
                    );


                _server = new KestrelServer(kestrelServerOptions, transportFactory, loggerFactory);
                var diagnosticListener = new DiagnosticListener("a");
                var formOptions        = Options.Create(new FormOptions());
                IHttpContextFactory httpContextFactory = new HttpContextFactory(formOptions);
                app = new HostingApplication(
                    RequestDelegate,
                    loggerFactory.CreateLogger <KestrelWebServer>(),
                    diagnosticListener,
                    httpContextFactory
                    );
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
                return;
            }

            var   kestrelStartup = _server.StartAsync(app, _cancellationTokenSource.Token);
            await kestrelStartup;

            _cancellationTokenSource.Token.Register(
                state => ((IApplicationLifetime)state).StopApplication(),
                _applicationLifetime
                );
            var completionSource = new TaskCompletionSource <object>(
                TaskCreationOptions.RunContinuationsAsynchronously
                );

            _applicationLifetime.ApplicationStopping.Register(
                obj => ((TaskCompletionSource <object>)obj).TrySetResult(null),
                completionSource
                );
            var   kestrelCompleted       = completionSource.Task;
            var   kestrelCompletedResult = await kestrelCompleted;
            var   kestrelShutdown        = _server.StopAsync(new CancellationToken());
            await kestrelShutdown;
        }
Esempio n. 22
0
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        HostingEventSource.Log.HostStart();

        var serverAddressesFeature = Server.Features.Get <IServerAddressesFeature>();
        var addresses = serverAddressesFeature?.Addresses;

        if (addresses != null && !addresses.IsReadOnly && addresses.Count == 0)
        {
            var urls = Configuration[WebHostDefaults.ServerUrlsKey];
            if (!string.IsNullOrEmpty(urls))
            {
                serverAddressesFeature !.PreferHostingUrls = WebHostUtilities.ParseBool(Configuration, WebHostDefaults.PreferHostingUrlsKey);

                foreach (var value in urls.Split(';', StringSplitOptions.RemoveEmptyEntries))
                {
                    addresses.Add(value);
                }
            }
        }

        RequestDelegate?application = null;

        try
        {
            var configure = Options.ConfigureApplication;

            if (configure == null)
            {
                throw new InvalidOperationException($"No application configured. Please specify an application via IWebHostBuilder.UseStartup, IWebHostBuilder.Configure, or specifying the startup assembly via {nameof(WebHostDefaults.StartupAssemblyKey)} in the web host configuration.");
            }

            var builder = ApplicationBuilderFactory.CreateBuilder(Server.Features);

            foreach (var filter in StartupFilters.Reverse())
            {
                configure = filter.Configure(configure);
            }

            configure(builder);

            // Build the request pipeline
            application = builder.Build();
        }
        catch (Exception ex)
        {
            Logger.ApplicationError(ex);

            if (!Options.WebHostOptions.CaptureStartupErrors)
            {
                throw;
            }

            var showDetailedErrors = HostingEnvironment.IsDevelopment() || Options.WebHostOptions.DetailedErrors;

            application = ErrorPageBuilder.BuildErrorPageApplication(HostingEnvironment.ContentRootFileProvider, Logger, showDetailedErrors, ex);
        }

        var httpApplication = new HostingApplication(application, Logger, DiagnosticListener, ActivitySource, Propagator, HttpContextFactory);

        await Server.StartAsync(httpApplication, cancellationToken);

        if (addresses != null)
        {
            foreach (var address in addresses)
            {
                Log.ListeningOnAddress(LifetimeLogger, address);
            }
        }

        if (Logger.IsEnabled(LogLevel.Debug))
        {
            foreach (var assembly in Options.WebHostOptions.GetFinalHostingStartupAssemblies())
            {
                Log.StartupAssemblyLoaded(Logger, assembly);
            }
        }

        if (Options.HostingStartupExceptions != null)
        {
            foreach (var exception in Options.HostingStartupExceptions.InnerExceptions)
            {
                Logger.HostingStartupAssemblyError(exception);
            }
        }
    }
        private Func <Microsoft.AspNetCore.Http.RequestDelegate, Microsoft.AspNetCore.Http.RequestDelegate> RequestDispatch(HostingApplication hostingApplication, CancellationToken cancellationToken)
        {
            return(next => async(context) =>
            {
                context.Response.ContentType = "application/json";
                OwinContext owinContext = null;
                try
                {
                    owinContext = hostingApplication.CreateContext(context);
                    await hostingApplication.ProcessRequestAsync(owinContext);
                }
                catch (Exception ex)
                {
                    owinContext.Response.Error(ex.Message);
                    throw;
                }
                finally
                {
                    context.Response.StatusCode = owinContext.Response.StatusCode;
                    string text = _serializer.Serialize(owinContext.Response);
                    await context.Response.WriteAsync(text, Encoding.UTF8, cancellationToken);

                    hostingApplication.DisponseContext(owinContext);
                }
            });
        }