Example #1
0
        public DefaultWebHostConfiguration ConfigureAppSettings()
        {
            _builder.ConfigureAppConfiguration((WebHostBuilderContext hostingContext, IConfigurationBuilder config) =>
            {
#if NETCOREAPP2_2 || NETSTANDARD2_0
                IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
#else
                IWebHostEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
#endif
                config
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", optional: true, reloadOnChange: true);

                if (hostingEnvironment.IsDevelopment())
                {
                    var assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
                    if (assembly != null)
                    {
                        config.AddUserSecrets(assembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();
                if (_cliArgs != null)
                {
                    config.AddCommandLine(_cliArgs);
                }
            });

            return(this);
        }
Example #2
0
        public static IWebHost BuildWebHost()
        {
            string root = Directory.GetCurrentDirectory();

            Console.WriteLine(String.Format("Working Directory: {0}", root));

            WebHostBuilder wb = new WebHostBuilder();

            wb.UseContentRoot(root);
            wb.UseKestrel();
            wb.ConfigureAppConfiguration((builderContext, config) => {
                IHostingEnvironment env = builderContext.HostingEnvironment;
                string app_settings     = $"appsettings.{env.EnvironmentName}.json";
                Console.WriteLine($"Loading Configuration: " + app_settings);
                config.AddJsonFile(app_settings, optional: true, reloadOnChange: true);
            });

            wb.UseIISIntegration();
            wb.UseDefaultServiceProvider((context, options) => {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            });
            wb.UseStartup <Startup>();
            //wb.UseUrls("172.18.82.145:5001");
            wb.UseUrls("http://0.0.0.0:5001");
            return(wb.Build());
        }
Example #3
0
        public static void Main(string[] args)
        {
            Mapper.RegisterConverter <Model.User, Database.Entities.User>(new UserConverter().ConvertToEntity);
            Mapper.RegisterConverter <Database.Entities.User, Model.User>(new UserConverter().ConvertToModel);

            var host = new WebHostBuilder();

            host.UseKestrel();
            host.UseContentRoot(System.IO.Directory.GetCurrentDirectory());

            host.ConfigureAppConfiguration((context, configuration) =>
            {
                var environment = context.HostingEnvironment;

                configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"/run/secrets/appsettings_shared.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"/run/secrets/appsettings_directory.json", optional: true, reloadOnChange: true);
                configuration.AddEnvironmentVariables();
            });

            host.ConfigureLogging((context, logging) =>
            {
                logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            });

            host.UseStartup <Startup>();
            host.Build().Run();
        }
Example #4
0
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            IWebHostBuilder builder = new WebHostBuilder();

            // Load Configs.
            builder.UseConfiguration(new ConfigurationBuilder().AddJsonFile("config/hostConfig.json").Build());
            // AppConfiguration is layered on top of a copy of the hostConfig.
            // The configs-delegates are run after the host config is built.
            builder.ConfigureAppConfiguration(configBuilder => { configBuilder.AddJsonFile("config/webConfig.json"); });

            // ContentRoot: AppContext.BaseDirectory is the default (WebHostBuilder.BuildCommonServices() called by IWebHost.Build()).
            builder.UseContentRoot(AppContext.BaseDirectory);
            // WebRoot: wwwroot is the default (HostingEnvironmentExtensions.Initialize() called by WebHostBuilder.BuildCommonServices())
            builder.UseWebRoot("wwwroot");


            // Register Services with IoC container.
            builder.ConfigureServices(ConfigureCommanderServices());
            // WebHost calls the 2 methods of Startup to configure the pipeline during Start().
            builder.ConfigureServices(AddStartup());
            // The DI registration for IServer.
            builder.UseKestrel();

            return(builder);
        }
Example #5
0
        static void Main(string[] args)
        {
            var builder = new WebHostBuilder();

            builder.UseContentRoot(Directory.GetCurrentDirectory());
            builder.UseKestrel((builderContext, options) =>
            {
                options.Listen(IPAddress.Any, 50500);
            });
            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.AddEnvironmentVariables();
                if (env.IsDevelopment())
                {
                    config.AddUserSecrets <Program>();
                }
            });
            builder.ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole();
            });
            builder.UseStartup <Startup>();

            var host = builder.Build();

            host.Run();
        }
Example #6
0
        public override void SetUp()
        {
            theCheck = new RecordingEnvironmentCheck();

            var builder = new WebHostBuilder();

            builder.UseUrls("http://localhost:3456");
            //builder.UseKestrel();
            builder.ConfigureServices(x =>
            {
                x.AddSingleton <IService, Service>();
                x.AddSingleton <IEnvironmentCheck>(theCheck);
            });

            builder.ConfigureAppConfiguration(b =>
            {
                b.AddInMemoryCollection(new Dictionary <string, string> {
                    { "city", "Austin" }
                });
            });


            builder.UseStartup <AppStartUp>();
            builder.UseEnvironment("Green");
            builder.UseJasper <BootstrappingApp>();


            theHost = builder.Build();


            theContainer = theHost.Services.As <IContainer>();
            theHost.Start();
        }
Example #7
0
        private void ConfigureConfiguration()
        {
            if (Args != null)
            {
                _builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(Args).Build());
            }

            _builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.local.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (Args != null)
                {
                    config.AddCommandLine(Args);
                }
            });
        }
Example #8
0
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            //WebHost.CreateDefaultBuilder(args)
            //    .UseStartup<Startup>();

            var builder = new WebHostBuilder();

            builder
            .ConfigureAppConfiguration(b => {
                b.AddJsonFile("appsettings.json");//add default settings
                b.AddConsul(consul => {
                    consul.Address = new Uri("http://localhost:8500");
                });
            })
            .ConfigureServices(services => {
            })
            .ConfigureLogging(log =>
            {
                log.ClearProviders();
                log.AddConsole();
                log.SetMinimumLevel(LogLevel.Trace);
                log.AddFilter((n, l) => !n.StartsWith("Microsoft."));
            })
            .UseKestrel()
            .UseSockets()
            .UseContentRoot(Directory.GetCurrentDirectory())
            //.UseUrls($"http://localhost:{NetHelper.GetAvailablePort()}")
            .UseUrls("http://localhost:54469")
            .UseStartup <Startup>();

            return(builder);
        }
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder();

            host.UseKestrel();
            host.UseContentRoot(Directory.GetCurrentDirectory());

            host.ConfigureAppConfiguration((context, configuration) =>
            {
                var environment = context.HostingEnvironment;

                configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"/run/secrets/appsettings_shared.json", optional: true, reloadOnChange: true);
                configuration.AddJsonFile($"/run/secrets/appsettings_api.json", optional: true, reloadOnChange: true);
                configuration.AddEnvironmentVariables();
            });

            host.ConfigureLogging((context, logging) =>
            {
                logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            });

            host.UseStartup <Startup>();
            host.Build().Run();
        }
Example #10
0
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            var builder = new WebHostBuilder();

            builder.ConfigureAppConfiguration((context, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("hosting.json", optional: true);

                if (System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
                {
                    config.AddJsonFile("appsettings.Development.json", optional: false, reloadOnChange: true);
                }
                else
                {
                    var env = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                    config.AddJsonFile($"appsettings.{env}.json", optional: false, reloadOnChange: true);
                }

                // var settings = config.Build();
                // var connection = settings.GetConnectionString("AppConfig");
                // config.AddAzureAppConfiguration(connection);
                config.AddEnvironmentVariables();
                _configuration = config.Build();
            });
            return(builder);
        }
        public BaseApiTest()
        {
            // Arrange test enviromnent
            var builder = new WebHostBuilder();

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddJsonFile("config/appsettings.json", optional: true, reloadOnChange: true);
                config.AddJsonFile(
                    $"config/appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json",
                    optional: true);
                config.AddEnvironmentVariables();
            })
            .UseStartup <Startup>();

            // Load environment variables
            LoadEnvironmentVariables();

            // Start test server
            TestServer testServer = new TestServer(builder);

            _apiClient = testServer.CreateClient();

            // Set services
            _testService    = testServer.Services.GetService <ITestService>();
            _infrastructure = testServer.Services.GetService <IInfrastructureService>();

            // Crate fake HttpContext
            CreateDefaultHttpContext();
        }
Example #12
0
        public static IWebHostBuilder BuildWebHostBuilder(string[] args)
        {
            // TEMP CONFIG BUILDER TO GET THE VALUES IN THE ELASTIC BEANSTALK CONFIG
            IConfigurationBuilder tempConfigBuilder = new ConfigurationBuilder();

            tempConfigBuilder.AddJsonFile(
                @"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration",
                optional: true,
                reloadOnChange: true
                );

            IConfigurationRoot tempConfig = tempConfigBuilder.Build();

            Dictionary <string, string> ebConfig = ConfigurationBuilderExtensions.GetConfig(tempConfig);

            // START WEB HOST BUILDER
            IWebHostBuilder builder = new WebHostBuilder()
                                      .UseKestrel()
                                      .UseContentRoot(Directory.GetCurrentDirectory());

            // CHECK IF EBCONFIG HAS ENVIRONMENT KEY IN IT
            // IF SO THEN CHANGE THE BUILDERS ENVIRONMENT
            const string envKey = "ASPNETCORE_ENVIRONMENT";

            if (ebConfig.ContainsKey(envKey))
            {
                string ebEnvironment = ebConfig[envKey];
                builder.UseEnvironment(ebEnvironment);
            }

            // CONTINUE WITH WEB HOST BUILDER AS NORMAL
            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                IHostingEnvironment env = hostingContext.HostingEnvironment;

                // ADD THE ELASTIC BEANSTALK CONFIG DICTIONARY
                config.AddJsonFile(
                    "appsettings.json",
                    optional: false,
                    reloadOnChange: true
                    )
                .AddJsonFile(
                    $"appsettings.{env.EnvironmentName}.json",
                    optional: true,
                    reloadOnChange: true
                    )
                .AddInMemoryCollection(ebConfig);


                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .UseIISIntegration();

            return(builder);
        }
        private static void ConfigureAppConfiguration(string[] args, WebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                var configurationBuilder = new ConfigurationBuilder();

                if (env.EnvironmentName == EnvironmentName.Development || env.EnvironmentName == EnvironmentName.Qa)
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        configurationBuilder.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                configurationBuilder.AddEnvironmentVariables();
                if (args != null)
                {
                    configurationBuilder.AddCommandLine(args);
                }

                var initialAppConfig = new AppConfig(configurationBuilder);
                configurationBuilder = new ConfigurationBuilder();
                configurationBuilder.AddAzureAppConfiguration(initialAppConfig.AppConfigurationConnectionString);
                var azureAppConfigConfig = new AppConfig(configurationBuilder);
                config.AddConfiguration(azureAppConfigConfig.Configuration);
                config.AddAzureKeyVault(
                    $"https://{azureAppConfigConfig.Global.KeyVault.Name}.vault.azure.net/",
                    azureAppConfigConfig.Global.AzureActiveDirectory.AppId,
                    azureAppConfigConfig.Global.AzureActiveDirectory.AppSecret);
                config.AddConfiguration(initialAppConfig.Configuration);
                azureAppConfig = azureAppConfigConfig;
            });
        }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebHostBuilder"/> class with pre-configured defaults.
        /// </summary>
        /// <remarks>
        ///   The following defaults are applied to the returned <see cref="WebHostBuilder"/>:
        ///     use Kestrel as the web server and configure it using the application's configuration providers,
        ///     set the <see cref="IHostEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/>,
        ///     load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostEnvironment.EnvironmentName"/>].json',
        ///     load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
        ///     load <see cref="IConfiguration"/> from environment variables,
        ///     load <see cref="IConfiguration"/> from supplied command line args,
        ///     configure the <see cref="ILoggerFactory"/> to log to the console and debug output,
        ///     configure the <see cref="IWebHostEnvironment.WebRootFileProvider"/> to map static web assets when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
        ///     adds the HostFiltering middleware,
        ///     adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true,
        ///     and enable IIS integration.
        /// </remarks>
        /// <param name="args">The command line args.</param>
        /// <returns>The initialized <see cref="IWebHostBuilder"/>.</returns>
        public static IWebHostBuilder CreateDefaultBuilder(string[]?args)
        {
            var builder = new WebHostBuilder();

            if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }
            if (args != null)
            {
                builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
            }

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .ConfigureLogging((hostingContext, loggingBuilder) =>
            {
                loggingBuilder.Configure(options =>
                {
                    options.ActivityTrackingOptions = ActivityTrackingOptions.SpanId
                                                      | ActivityTrackingOptions.TraceId
                                                      | ActivityTrackingOptions.ParentId;
                });
                loggingBuilder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                loggingBuilder.AddConsole();
                loggingBuilder.AddDebug();
                loggingBuilder.AddEventSourceLogger();
            }).
            UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            });

            ConfigureWebDefaults(builder);

            return(builder);
        }
Example #15
0
 public TestBase(TestFixture testFixture)
 {
     DbContext   = testFixture.CreateDbContext();
     HostBuilder = new WebHostBuilder();
     HostBuilder.UseEnvironment("Testing").UseStartup <Startup>();
     HostBuilder.ConfigureAppConfiguration((Action <WebHostBuilderContext, IConfigurationBuilder>)
                                               ((builderContext, config) => config.AddJsonFile("appsettings.json")));
     TestingServer = new TestServer(HostBuilder);
     HttpClient    = TestingServer.CreateClient();
 }
Example #16
0
        public void ConfigureWebHostBuilder(ExecutionContext executionContext, WebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration(ConfigureAppConfiguration);
            builder.ConfigureLogging(Logging);

            if (environment.IsDevelopment())
            {
                builder.UseContentRoot(Path.Combine(Directory.GetCurrentDirectory(), "../../../../../src/DotNetDevOps.Web"));
            }
        }
Example #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebHostBuilder"/> class with pre-configured defaults.
        /// </summary>
        /// <remarks>
        ///   The following defaults are applied to the returned <see cref="WebHostBuilder"/>:
        ///     use Kestrel as the web server and configure it using the application's configuration providers,
        ///     set the <see cref="IHostingEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/>,
        ///     load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
        ///     load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
        ///     load <see cref="IConfiguration"/> from environment variables,
        ///     load <see cref="IConfiguration"/> from supplied command line args,
        ///     configure the <see cref="ILoggerFactory"/> to log to the console and debug output,
        ///     and enable IIS integration.
        /// </remarks>
        /// <param name="args">The command line args.</param>
        /// <returns>The initialized <see cref="IWebHostBuilder"/>.</returns>
        public static IWebHostBuilder CreateDefaultBuilder(string[] args)
        {
            var builder = new WebHostBuilder();

            if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }
            if (args != null)
            {
                builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
            }
            //查看运行环境
            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                //根据运行环境调用APP.json覆盖运行设置
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                //加载assembly程序集,运行系统的核心代码
                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            //设置日志,以及系统的上下文对象信息Context
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();
            }).
            UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            });
            //返回并且运行虚拟主机,创建程序
            ConfigureWebDefaults(builder);

            return(builder);
        }
        protected override IWebHostBuilder CreateWebHostBuilder()
        {
            var hostBuilder = new WebHostBuilder();

            // Solution fixing the problem:
            // https://github.com/dotnet/aspnetcore/issues/17655#issuecomment-581418168
            hostBuilder.ConfigureAppConfiguration((context, b) =>
            {
                context.HostingEnvironment.ApplicationName = typeof(ViewRender).Assembly.GetName().Name;
            });
            return(hostBuilder.UseStartup <ComponentTestStartup>());
        }
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            // To make the app production ready we need to configure the WebHostBuilder further.
            var builder = new WebHostBuilder();

            builder.UseContentRoot(Directory.GetCurrentDirectory());
            builder.ConfigureAppConfiguration(ConfigureAppConfiguration());
            builder.UseKestrel(ConfigureKestrel());
            builder.UseSerilog(ConfigureSeriLog());
            builder.UseStartup <Startup>();

            return(builder);
        }
        public void ConfigureWebHostBuilder(WebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration(ConfigureAppConfiguration);
            builder.ConfigureLogging(Logging);

            if (hostingEnvironment.IsDevelopment())
            {
                builder.UseContentRoot(Path.Combine(Directory.GetCurrentDirectory(), "../../.."));
            }
            // builder.UseContentRoot();
            //   builder.UseContentRoot(Directory.GetCurrentDirectory());
            // builder.UseContentRoot();
        }
        public static HttpClient Create()
        {
            var webhostBuilder = new WebHostBuilder();

            webhostBuilder.UseStartup <Startup>();
            webhostBuilder.ConfigureAppConfiguration((context, config) =>
            {
                config.AddJsonFile("appsettings.json");
            });

            var testServer = new TestServer(webhostBuilder);

            return(testServer.CreateClient());
        }
        private void SetupClient()
        {
            var projectDir = Directory.GetCurrentDirectory();
            var configPath = Path.Combine(projectDir, "appsettings.json");

            var webHost = new WebHostBuilder().UseStartup <Startup>();

            webHost.ConfigureAppConfiguration((context, conf) =>
            {
                conf.AddJsonFile(configPath);
            });

            _server = new TestServer(webHost);
            Client  = _server.CreateClient();
        }
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            //return WebHost.CreateDefaultBuilder(args)
            //    .UseUrls("http://localhost:8099")
            //    .ConfigureAppConfiguration((hostingContext, config) =>
            //    {
            //        config
            //            .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
            //            .AddJsonFile("appsettings.json", true, true)
            //            .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
            //            .AddJsonFile("ocelot.json", false, false)
            //            .AddEnvironmentVariables();
            //    })
            //    .ConfigureServices(s =>
            //    {
            //        s.AddOcelot().AddEureka().AddCacheManager(x => x.WithDictionaryHandle());
            //    })
            //    .Configure(a =>
            //    {
            //        a.UseOcelot().Wait();
            //    });

            IWebHostBuilder builder = new WebHostBuilder();

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                config
                .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                //.AddJsonFile("appsettings.json", true, true)
                //.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                .AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
                //.AddOcelot(hostingContext.HostingEnvironment)
                .AddEnvironmentVariables();
            });
            builder.ConfigureServices(s =>
            {
                s.AddSingleton(builder);
            });
            builder.UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup <Startup>()
            .UseUrls("http://localhost:9000");
            return(builder);
        }
Example #24
0
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder();

            host.UseKestrel();

            host.UseContentRoot(Directory.GetCurrentDirectory());

            host.ConfigureAppConfiguration((context, configuration) =>
            {
                configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

                configuration.AddEnvironmentVariables();
            });

            host.UseStartup <Startup>();

            host.Build().Run();
        }
Example #25
0
        public BancoDigitalGraphQLIntegrationTest()
        {
            var projectDir = Directory.GetCurrentDirectory();
            var configPath = Path.Combine(projectDir, "appsettings.json");

            var webHostBuilder = new WebHostBuilder();

            webHostBuilder.ConfigureAppConfiguration(o =>
            {
                o.AddJsonFile(configPath);
            });
            webHostBuilder.UseStartup <Startup>();

            var server = new TestServer(webHostBuilder);

            // Necessário para fazer requisições assíncronas
            server.AllowSynchronousIO = true;

            _client = server.CreateClient();
        }
Example #26
0
        public IWebHost BuildHost()
        {
            // SAMPLE: what-the-cli-is-doing

            // The --log-level flag value overrides your application's
            // LogLevel
            if (LogLevelFlag.HasValue)
            {
                Console.WriteLine($"Overwriting the minimum log level to {LogLevelFlag.Value}");
                WebHostBuilder.ConfigureLogging(x => x.SetMinimumLevel(LogLevelFlag.Value));
            }

            if (VerboseFlag)
            {
                Console.WriteLine("Verbose flag is on.");

                // The --verbose flag adds console and
                // debug logging, as well as setting
                // the minimum logging level down to debug
                WebHostBuilder.ConfigureLogging(x =>
                {
                    x.SetMinimumLevel(LogLevel.Debug);
                });
            }

            // The --environment flag is used to set the environment
            // property on the IHostedEnvironment within your system
            if (EnvironmentFlag.IsNotEmpty())
            {
                Console.WriteLine($"Overwriting the environment to `{EnvironmentFlag}`");
                WebHostBuilder.UseEnvironment(EnvironmentFlag);
            }

            if (ConfigFlag.Any())
            {
                WebHostBuilder.ConfigureAppConfiguration(c => c.AddInMemoryCollection(ConfigFlag));
            }
            // ENDSAMPLE

            return(WebHostBuilder.Build());
        }
Example #27
0
        /// <summary>
        /// Creates the in memory server and client for controller tests.
        /// </summary>
        /// <typeparam name="TStartup">The startup class for the server.</typeparam>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="configure">Action to add configuration providers to the server.</param>
        public static void CreateInMemoryServerAndClient <TStartup>(this ControllerContext controllerContext, Action <IConfigurationBuilder> configure)
            where TStartup : class
        {
            TestServer tempServer = null;
            HttpClient tempClient = null;

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

            try
            {
                WebHostBuilder builder = new WebHostBuilder();
                if (configure != null)
                {
                    builder.ConfigureAppConfiguration(configure);
                }

                builder.UseStartup <TStartup>();

                tempServer = new TestServer(builder);
                tempClient = tempServer.CreateClient();
                controllerContext.TestServer = tempServer;
                controllerContext.TestClient = tempClient;
                tempServer = null;
                tempClient = null;
            }
            finally
            {
                if (tempServer != null)
                {
                    tempServer.Dispose();
                }

                if (tempClient != null)
                {
                    tempClient.Dispose();
                }
            }
        }
Example #28
0
        public ApiFilterUnitTests()
        {
            var projectDir = Directory.GetCurrentDirectory();
            var configPath = Path.Combine(projectDir, "appsettings.json");

            var webhostBuilder = new WebHostBuilder();

            webhostBuilder.ConfigureAppConfiguration((context, conf) =>
            {
                conf.AddJsonFile(configPath);
            });
            webhostBuilder.UseStartup <Startup>();
            webhostBuilder.ConfigureTestServices(config =>
            {
                config.AddSingleton <IMockyService>(new MockProductClient());
            });

            var server = new TestServer(webhostBuilder);

            Client = server.CreateClient();
        }
Example #29
0
        public static async Task AssemblyInitializeAsync(TestContext testContext)
        {
            var projectDir = Directory.GetCurrentDirectory();
            var configPath = Path.Combine(projectDir, "appsettings.Development.json");
            var builder    = new WebHostBuilder();

            builder.ConfigureAppConfiguration((context, conf) =>
            {
                conf.AddJsonFile(configPath);
            });

            // Delete Database (Remove comment when need to test)
            //await DeleteEmulatorDatabase().ConfigureAwait(false);

            var _server = new TestServer(builder
                                         .UseStartup <PartyFindsApi.Startup>());

            AssemblyInit._client = _server.CreateClient();

            // TODO: Set up Test Application wide Data
            await InitTestScenarios();
        }
Example #30
0
        private static IWebHostBuilder createDefaultWebHostBuilder()
        {
            var builder = new WebHostBuilder();

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                config.AddEnvironmentVariables();
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            });

            return(builder);
        }