Пример #1
0
        protected override void ApplyConfiguration()
        {
            base.ApplyConfiguration();
            IServer server = _serviceProvider.GetRequiredService <IServer>();
            IServerAddressesFeature addresses = server.Features.Get <IServerAddressesFeature>();

            foreach (string address in addresses.Addresses)
            {
                if (!address.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                {
                    // IIS hosting can populate Addresses with net.tcp/net.pipe/net.msmq addresses
                    // if the site has those bindings
                    continue;
                }

                var fixedUri = FixUri(address);
                // ASP.NET Core assumes all listeners are http. Other transports such as NetTcp will already be populated
                // in the base addresses so filter them out.
                bool skip = false;
                foreach (var baseAddress in InternalBaseAddresses)
                {
                    if (baseAddress.Port == fixedUri.Port) // Already added with a different protocol
                    {
                        skip = true;
                        break;
                    }
                }

                if (!skip)
                {
                    AddBaseAddress(FixUri(address));
                }
            }
        }
Пример #2
0
 public DebugInfoPageMiddleware(RequestDelegate next, IServerAddressesFeature serverAddresses, IHostingEnvironment hostingEnv, Scenarios scenarios)
 {
     _next            = next;
     _hostingEnv      = hostingEnv;
     _scenarios       = scenarios;
     _serverAddresses = serverAddresses;
 }
Пример #3
0
        public void Start <TContext>(IHttpApplication <TContext> application)
        {
            IServerAddressesFeature addressFeatures = this.Features.Get <IServerAddressesFeature>();

            foreach (string address in addressFeatures.Addresses)
            {
                this.Listener.Prefixes.Add(address.TrimEnd('/') + "/");
            }

            this.Listener.Start();
            while (true)
            {
                HttpListenerContext httpListenerContext = this.Listener.GetContext();

                HttpListenerContextFeature feature         = new HttpListenerContextFeature(httpListenerContext, this.Listener);
                IFeatureCollection         contextFeatures = new FeatureCollection()
                                                             .Set <IHttpRequestFeature>(feature)
                                                             .Set <IHttpResponseFeature>(feature);
                TContext context = application.CreateContext(contextFeatures);

                application.ProcessRequestAsync(context)
                .ContinueWith(_ => httpListenerContext.Response.Close())
                .ContinueWith(_ => application.DisposeContext(context, _.Exception));
            }
        }
Пример #4
0
        public static async Task BindAsync(IServerAddressesFeature addresses,
                                           KestrelServerOptions serverOptions,
                                           ILogger logger,
                                           IDefaultHttpsProvider defaultHttpsProvider,
                                           Func <ListenOptions, Task> createBinding)
        {
            var listenOptions = serverOptions.ListenOptions;
            var strategy      = CreateStrategy(
                listenOptions.ToArray(),
                addresses.Addresses.ToArray(),
                addresses.PreferHostingUrls);

            var context = new AddressBindContext
            {
                Addresses            = addresses.Addresses,
                ListenOptions        = listenOptions,
                ServerOptions        = serverOptions,
                Logger               = logger,
                DefaultHttpsProvider = defaultHttpsProvider ?? UnconfiguredDefaultHttpsProvider.Instance,
                CreateBinding        = createBinding
            };

            // reset options. The actual used options and addresses will be populated
            // by the address binding feature
            listenOptions.Clear();
            addresses.Addresses.Clear();

            await strategy.BindAsync(context).ConfigureAwait(false);
        }
        public KestrelServer(IOptions <KestrelServerOptions> options, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (applicationLifetime == null)
            {
                throw new ArgumentNullException(nameof(applicationLifetime));
            }

            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            Options = options.Value ?? new KestrelServerOptions();
            _applicationLifetime = applicationLifetime;
            _logger  = loggerFactory.CreateLogger(typeof(KestrelServer).GetTypeInfo().Assembly.FullName);
            Features = new FeatureCollection();
            var componentFactory = new HttpComponentFactory(Options);

            Features.Set <IHttpComponentFactory>(componentFactory);
            _serverAddresses = new ServerAddressesFeature();
            Features.Set <IServerAddressesFeature>(_serverAddresses);
        }
 public DebugInfoPageMiddleware(RequestDelegate next, IServerAddressesFeature serverAddresses, IHostingEnvironment hostingEnv, Scenarios scenarios)
 {
     _next = next;
     _hostingEnv = hostingEnv;
     _scenarios = scenarios;
     _serverAddresses = serverAddresses;
 }
 private void BuildResponse_Default(HttpContext context, IServerAddressesFeature serverAddressesFeature)
 {
     try
     {
         bool hasForm = context.Request.HasFormContentType && context.Request.Form.Count > 0;
         context.Response.ContentType = "text/html";
         context.Response.WriteAsync("<!DOCTYPE html><html lang=\"en\"><head><title></title></head><body><p>Hosted by Kestrel</p>");
         if (serverAddressesFeature != null)
         {
             context.Response.WriteAsync("<p>Listening on the following addresses: " + string.Join(", ", serverAddressesFeature.Addresses) + "</p>");
         }
         context.Response.WriteAsync($"<p>Request URL: {context.Request.GetDisplayUrl()}<p>");
         if (hasForm && context.Request.Form.Count > 0)
         {
             context.Response.WriteAsync("<p>Form submitted! (POST)");
             foreach (string key in context.Request.Form.Keys)
             {
                 context.Response.WriteAsync($"<br> - Field [{key}]: '{context.Request.Form[key]}'");
             }
             context.Response.WriteAsync("<br></p>");
         }
         context.Response.WriteAsync($"<p>Number of total requests: {countRequests}</p>");
         context.Response.WriteAsync("</body></html>");
     }
     catch (Exception exception) { BackEnd.WriteResponseError(context, exception.Message); }
 }
 private static string[] GetTestUrls(IServerAddressesFeature addressesFeature)
 {
     return(addressesFeature.Addresses
            .Select(a => a.Replace("://+", "://localhost"))
            .Select(a => a.EndsWith("/") ? a : a + "/")
            .ToArray());
 }
        public static async Task BindAsync(IServerAddressesFeature addresses,
                                           List <ListenOptions> listenOptions,
                                           ILogger logger,
                                           Func <ListenOptions, Task> createBinding)
        {
            var strategy = CreateStrategy(
                listenOptions.ToArray(),
                addresses.Addresses.ToArray(),
                addresses.PreferHostingUrls);

            var context = new AddressBindContext
            {
                Addresses     = addresses.Addresses,
                ListenOptions = listenOptions,
                Logger        = logger,
                CreateBinding = createBinding
            };

            // reset options. The actual used options and addresses will be populated
            // by the address binding feature
            listenOptions.Clear();
            addresses.Addresses.Clear();

            await strategy.BindAsync(context).ConfigureAwait(false);
        }
Пример #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            IServerAddressesFeature addresses = app.ServerFeatures[typeof(IServerAddressesFeature)] as IServerAddressesFeature;
            var address = addresses.Addresses.First();

            address = address + "Neeo";
            app.UseNEEO(address);
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Пример #11
0
        private async void DoWork(object state)
        {
            if (!ExistsApp())
            {
                Console.WriteLine("WebAPI2CLI: waiting to have app");
                return;
            }


            serverAddresses = app.ServerFeatures.Get <IServerAddressesFeature>();
            if (serverAddresses == null)
            {
                Console.WriteLine("WebAPI2CLI: waiting to have server adresses");
                return;
            }

            _timer.Dispose();
            exec = new Executor(configuration, serverAddresses, api, app.ApplicationServices);
            await exec.Execute();

            if (!ShouldStay())
            {
                Environment.Exit(0);
            }
        }
Пример #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Executor"/> class.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 /// <param name="serverAddresses">The server addresses.</param>
 /// <param name="api">The API.</param>
 /// <param name="serviceProvider">The service provider.</param>
 public Executor(IConfiguration configuration, IServerAddressesFeature serverAddresses, IApiDescriptionGroupCollectionProvider api, IServiceProvider serviceProvider)
 {
     this.serverAddresses = serverAddresses;
     this.api             = api;
     this.serviceProvider = serviceProvider;
     this.configuration   = configuration;
 }
Пример #13
0
        private static void RegisterServices(
            IApplicationBuilder builder,
            IHostApplicationLifetime lifetime,
            IConsulClient consulClient,
            ILogger <IApplicationBuilder> logger)
        {
            var registrations = new List <AgentServiceRegistration>();

            // Get discoverable services
            IEnumerable <DiscoverableServiceAttribute?> serviceDetails = AppDomain.CurrentDomain.GetAssemblies()
                                                                         .Where(ass => !ass.GlobalAssemblyCache)
                                                                         .SelectMany(ass => ass
                                                                                     .GetTypes()
                                                                                     .SelectMany(type => type.GetCustomAttributes <DiscoverableServiceAttribute>())
                                                                                     .Where(ds => ds != null));

            // Get server IP address
            if (builder.Properties["server.Features"] is FeatureCollection features)
            {
                IServerAddressesFeature addresses = features.Get <IServerAddressesFeature>();
                foreach (string address in addresses.Addresses)
                {
                    var    uri         = new Uri(address);
                    string hostAddress = $"{uri.Scheme}://{uri.Host}";
                    foreach (DiscoverableServiceAttribute?service in serviceDetails)
                    {
                        // Register service with consul
                        string serviceId = $"{service!.ServiceName}-{service!.ServiceType}";
                        logger.LogDebug($"Registering service '{serviceId}' with Consul using address {hostAddress}:{uri.Port}");
                        var registration = new AgentServiceRegistration()
                        {
                            ID      = serviceId,
                            Name    = service !.ServiceName,
                            Address = hostAddress,
                            Port    = uri.Port,
                            Tags    = service.Tags.Prepend(service !.ServiceType).ToArray()
                        };
                        registrations.Add(registration);
                        consulClient.Agent.ServiceDeregister(registration.ID).Wait();
                        consulClient.Agent.ServiceRegister(registration).Wait();
                    }
                }
            }

            if (registrations.Any())
            {
                logger.LogInformation($"Registered {registrations.Count} services with Consul");


                lifetime.ApplicationStopping.Register(() =>
                {
                    foreach (AgentServiceRegistration registration in registrations)
                    {
                        consulClient.Agent.ServiceDeregister(registration.ID).Wait();
                    }
                    logger.LogInformation("Unregistered from Consul");
                });
            }
        }
    }
Пример #14
0
        private void EnsureBaseAddresses()
        {
            if (_serverAddresses != null)
            {
                foreach (var addr in _serverAddresses.Addresses)
                {
                    var  uri  = new Uri(addr);
                    bool skip = false;
                    foreach (var baseAddress in InternalBaseAddresses)
                    {
                        if (baseAddress.Port == uri.Port && baseAddress.Scheme != uri.Scheme)
                        {
                            // ASP.NET Core adds net.tcp uri's as http{s} uri's
                            skip = true;
                            break;
                        }
                    }
                    if (!skip && !InternalBaseAddresses.Contains(uri))
                    {
                        InternalBaseAddresses.Add(uri);
                    }
                }

                if (_serverAddresses.Addresses.Count > 0)
                {
                    // It was populated by ASP.NET Core so can skip re-adding in future.
                    _serverAddresses = null;
                }
            }
        }
Пример #15
0
        // For testing
        internal SimpleServer(ServiceContext serviceContext)
        {
            ServiceContext = serviceContext;

            Features         = new FeatureCollection();
            _serverAddresses = new ServerAddressesFeature();
            Features.Set(_serverAddresses);
        }
Пример #16
0
 /// <summary>
 ///     Initializes the HttpsRedirectionMiddleware
 /// </summary>
 /// <param name="next"></param>
 /// <param name="options"></param>
 /// <param name="config"></param>
 /// <param name="loggerFactory"></param>
 /// <param name="serverAddressesFeature">The</param>
 public HttpsRedirectionMiddleware(RequestDelegate next, IOptions <HttpsRedirectionOptions> options,
                                   IConfiguration config, ILoggerFactory loggerFactory,
                                   IServerAddressesFeature serverAddressesFeature)
     : this(next, options, config, loggerFactory)
 {
     _serverAddressesFeature =
         serverAddressesFeature ?? throw new ArgumentNullException(nameof(serverAddressesFeature));
 }
Пример #17
0
        public static void Main(string[] args)
        {
            _webHost = CreateWebHostBuilder(args).Build();

            IServerAddressesFeature serverAddressesFeature = _webHost.ServerFeatures.Get <IServerAddressesFeature>();

            _webHost.Run();
        }
Пример #18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            _serverAddressesFeature = app.ServerFeatures.Get <IServerAddressesFeature>();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Demo/Error");
            }

            app.UseResponseCompression();

            app.UseStaticFiles();

            // app.UseCookiePolicy();

            app.UseResponseCaching();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            /*
             * app.Use((context, next) =>
             * {
             *  var endpointFeature = context.Features[typeof(IEndpointFeature)] as IEndpointFeature;
             *  var endpoint = endpointFeature?.Endpoint;
             *
             *  if (endpoint != null)
             *  {
             *      var metadataCollection = endpoint?.Metadata;
             *      var pattern = (endpoint as RouteEndpoint)?.RoutePattern?.RawText;
             *
             *      Console.WriteLine("Name: " + endpoint.DisplayName);
             *      Console.WriteLine($"Route Pattern: {pattern}");
             *      Console.WriteLine("Metadata Types: " + string.Join(", ", metadataCollection));
             *  }
             *  return next();
             * });
             */

            app.UseEndpoints(route =>
            {
                route.MapHub <QuotesHub>("/quotes");

                route.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{action=Index}/{id?}",
                    defaults: new { controller = "Demo", action = "Index" }
                    );
            });
        }
Пример #19
0
        public ServiceHostObjectModel(IServiceProvider serviceProvider, IServer server, IServiceBuilder serviceBuilder, ILogger <ServiceHostObjectModel <TService> > logger)
        {
            _serviceProvider = serviceProvider;
            _serverAddresses = server.Features.Get <IServerAddressesFeature>();
            _logger          = logger;

            InitializeBaseAddresses(serviceBuilder);

            InitializeDescription(new UriSchemeKeyedCollection(serviceBuilder.BaseAddresses.ToArray()));
        }
Пример #20
0
        public GatewayClient(IServer server, EndpointDataSource endpointDataSource, IOptions <ServiceOptions> options)
        {
            _serverAddresses    = server.Features.Get <IServerAddressesFeature>();
            _endpointDataSource = endpointDataSource;

            GrpcClientFactory.AllowUnencryptedHttp2 = true;

            var http = GrpcChannel.ForAddress(options.Value.GatewayAddress);

            _gateway = http.CreateGrpcService <IGatewayService>();
        }
Пример #21
0
        private static void PrintRuntimeInfo(IWebHostEnvironment environment, IServerAddressesFeature serverAddressesFeature)
        {
            var addresses = serverAddressesFeature.Addresses;

            Console.WriteLine($"Content: {environment.WebRootPath}");

            foreach (var address in addresses)
            {
                Console.WriteLine($"Listening: {address}");
            }
        }
Пример #22
0
 public DevicesController(
     ILogger <DevicesController> logger,
     IServerAddressesFeature serverAddresses,
     IDevicesService <TDevices> devicesService,
     IMapper mapper
     )
 {
     _logger          = logger;
     _serverAddresses = serverAddresses;
     _devicesService  = devicesService;
     _mapper          = mapper;
 }
Пример #23
0
 public SensorsController(
     ILogger <SensorsController> logger,
     IServerAddressesFeature serverAddresses,
     ISensorService <TSensors> sensorService,
     IMapper mapper
     )
 {
     _logger          = logger;
     _serverAddresses = serverAddresses;
     _sensorService   = sensorService;
     _mapper          = mapper;
 }
Пример #24
0
        private static void PrintSwaggerUrl(IServerAddressesFeature serverAddressFeature)
        {
            if (serverAddressFeature == null)
            {
                return;
            }

            foreach (var address in serverAddressFeature.Addresses)
            {
                Console.WriteLine($"Swagger Open API is available on: {address}/swagger");
            }
        }
Пример #25
0
 public ProjectsController(
     ILogger <ProjectsController> logger,
     IServerAddressesFeature serverAddresses,
     IProjectsService <TProjects> projectsService,
     IMapper mapper
     )
 {
     _logger          = logger;
     _serverAddresses = serverAddresses;
     _projectsService = projectsService;
     _mapper          = mapper;
 }
Пример #26
0
 public CaddyFastCgiServer(
     FastCgiServer fastCgiServer,
     IOptions <FastCgiServerOptions> fastCgiOptions,
     IOptions <CaddyServerOptions> caddyOptions)
 {
     this.fastCgiServer  = fastCgiServer;
     this.fastCgiOptions = fastCgiOptions;
     this.caddyOptions   = caddyOptions;
     serverAddresses     = new ServerAddressesFeature();
     Features.Set(serverAddresses);
     caddyfilePath = Path.Combine(Environment.CurrentDirectory, "Caddyfile");
 }
Пример #27
0
        /// <summary>
        /// 开始监听来自网络的HTTP请求。HTTP请求一旦抵达,我们会调用HttpListener的GetContext方法得到表示原始HTTP上下文的HttpListenerContext对象,
        /// 并根据它创建一个类型为HttpListenerContextFeature的特性对象,该对象分别采用类型IHttpRequestFeature和IHttpResponseFeature注册到创建的FeatureCollection对象上
        /// </summary>
        /// <typeparam name="TContext"></typeparam>
        /// <param name="application"></param>
        public void Run <TContext>(IHttpApplication <TContext> application) where TContext : Context
        {
            IServerAddressesFeature addressFeatures = this.Features.Get <IServerAddressesFeature>();

            // 添加监视地址
            foreach (string address in addressFeatures.Addresses)
            {
                Listener.Prefixes.Add(address.TrimEnd('/') + "/");
            }

            this.Listener.Start();
            this.Listener.BeginGetContext(GetServerCallback <TContext>, application); // 用异步方式监听HTTP请求
        }
Пример #28
0
        /// <summary>
        /// Returns first value in <see cref="IServerAddressesFeature.Addresses"/>.
        /// </summary>
        /// <param name="feature"></param>
        /// <returns></returns>
        public static string GetLaunchUrl(this IServerAddressesFeature feature)
        {
            if (feature == null)
            {
                return(null);
            }

            if (feature.Addresses != null && feature.Addresses.Count > 0)
            {
                return(feature.Addresses.FirstOrDefault());
            }

            return(null);
        }
Пример #29
0
 public AccountController(
     ILogger <AccountController> logger,
     IServerAddressesFeature serverAddresses,
     IAuthenticationService authenticationService,
     ISysUserServices <TSysUsers> userServices,
     IMapper mapper
     )
 {
     _logger                = logger;
     _serverAddresses       = serverAddresses;
     _authenticationService = authenticationService;
     _userServices          = userServices;
     _mapper                = mapper;
 }
Пример #30
0
 public SensorService
 (
     IAIOTCloudContext context,
     IServerAddressesFeature serverAddresses,
     IAuthenticationService authenticationService,
     ILogger <SensorService> logger,
     IMapper mapper
 )
 {
     _logger                = logger;
     _context               = context;
     _serverAddresses       = serverAddresses;
     _authenticationService = authenticationService;
     _mapper                = mapper;
 }
Пример #31
0
        // For testing
        internal KestrelServer(ITransportFactory transportFactory, ServiceContext serviceContext)
        {
            if (transportFactory == null)
            {
                throw new ArgumentNullException(nameof(transportFactory));
            }

            _transportFactory = transportFactory;
            ServiceContext    = serviceContext;

            Features         = new FeatureCollection();
            _serverAddresses = new ServerAddressesFeature();
            Features.Set(_serverAddresses);

            HttpCharacters.Initialize();
        }