// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); HostingHelper.Initialize(env); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime, ILogger <Startup> logger) { var instance = HostingHelper.GetWebsiteInstanceId(); applicationLifetime.ApplicationStarted.Register(() => logger.LogInformation($"Host fully started: ({instance})")); applicationLifetime.ApplicationStopping.Register(() => logger.LogInformation($"Host shutting down...waiting to complete requests: ({instance})")); applicationLifetime.ApplicationStopped.Register(() => logger.LogInformation($"Host fully stopped. All requests processed: ({instance})")); if (env.IsDevelopment()) { var configuration = (TelemetryConfiguration)app.ApplicationServices.GetService(typeof(TelemetryConfiguration)); configuration.DisableTelemetry = true; app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); app.UseAuthentication(); } app.ConfigureExceptionHandler(app.ApplicationServices.GetService <ILogger <ExceptionHandlerFeature> >()); app.UseHttpsRedirection(); app.UseHealthChecks("/health", new HealthCheckOptions { Predicate = _ => true }); app.UseMvc(); }
private async void WriteToFile(string cfg) { var path = HostingHelper.GetAppDirectory() + "\\" + Constants.AppConfigurationFileName; using (StreamWriter writer = File.CreateText(path)) { await writer.WriteLineAsync(cfg); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime, ILogger <Startup> logger) { var instance = HostingHelper.GetWebsiteInstanceId(); applicationLifetime.ApplicationStarted.Register(() => logger.LogInformation($"Host fully started: ({instance})")); applicationLifetime.ApplicationStopping.Register(() => logger.LogInformation($"Host shutting down...waiting to complete requests: ({instance})")); applicationLifetime.ApplicationStopped.Register(() => logger.LogInformation($"Host fully stopped. All requests processed: ({instance})")); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "RecruitAPI"); c.RoutePrefix = string.Empty; }); if (env.IsDevelopment()) { var configuration = (TelemetryConfiguration)app.ApplicationServices.GetService(typeof(TelemetryConfiguration)); configuration.DisableTelemetry = true; app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); app.UseAuthentication(); } app.ConfigureExceptionHandler(app.ApplicationServices.GetService <ILogger <ExceptionHandlerFeature> >()); app.UseHttpsRedirection(); app.UseHealthChecks("/health", new HealthCheckOptions { Predicate = _ => true }); app.UseRouting(); app.UseEndpoints(builder => { builder.MapControllerRoute( name: "default", pattern: "api/{controller=Vacancies}/{action=Index}/{id?}"); }); }
public static void Main(string[] args) { var instance = HostingHelper.GetWebsiteInstanceId();; var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Info($"Starting up host: ({instance})"); var host = CreateWebHostBuilder(args).Build(); host.Run(); } catch (Exception ex) { //NLog: catch setup errors logger.Fatal(ex, "Stopped program because of exception"); throw; } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime, ILogger <Startup> logger) { var instance = HostingHelper.GetWebsiteInstanceId(); applicationLifetime.ApplicationStarted.Register(() => logger.LogInformation($"Host fully started: ({instance})")); applicationLifetime.ApplicationStopping.Register(() => logger.LogInformation($"Host shutting down...waiting to complete requests: ({instance})")); applicationLifetime.ApplicationStopped.Register(() => logger.LogInformation($"Host fully stopped. All requests processed: ({instance})")); if (env.IsDevelopment()) { var configuration = app.ApplicationServices.GetService <Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration>(); configuration.DisableTelemetry = true; app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseAuthentication(); app.UseHealthChecks("/health", new HealthCheckOptions { ResponseWriter = HealthCheckResponseWriter.WriteJsonResponse }); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Employer Favourites Api V1"); c.RoutePrefix = string.Empty; }); app.UseMvc(); }
private void Load() { var configText = string.Empty; if (HostingHelper.GetAppDirectory() == null) { using (var reader = new StreamReader("..\\..\\cilesta.config.json")) { configText = reader.ReadToEnd(); } } else { var path = HostingHelper.GetAppDirectory() + "\\" + Constants.AppConfigurationFileName; using (var reader = new StreamReader(path)) { configText = reader.ReadToEnd(); } } this.Configuration = JsonHelper.Deserialize <ConfigurationSectionCollection>(configText); }
private async Task MainInternalAsync(string[] args) { _cmdOptions = CommandLineOptions.Parse(args, _console); var appdir = _cmdOptions.MainAppDirectory.Value(); var staticServe = _cmdOptions.StaticServe.Value(); var componentBuild = _cmdOptions.BuildComponent.Value(); var cleanTemp = _cmdOptions.CleanTemp.HasValue(); if (cleanTemp) { PathUtility.CleanTempDirectory(); } if (!string.IsNullOrEmpty(appdir)) { appdir = NormalizePath(appdir); if (Directory.Exists(appdir)) { _console.Out.WriteLine("Main application directory is: " + appdir); appdir = PathUtility.NormalizeRelavitePath(Directory.GetCurrentDirectory(), appdir); HostingHelper.MainAppDirectory = Path.GetFullPath(appdir); } } if (!string.IsNullOrEmpty(staticServe)) { staticServe = NormalizePath(staticServe); if (Directory.Exists(staticServe)) { _console.Out.WriteLine("Static files directory is: " + staticServe); HostingHelper.StaticServe = staticServe; } } if (!string.IsNullOrEmpty(componentBuild)) { componentBuild = NormalizePath(componentBuild); if (Directory.Exists(componentBuild)) { ComponentInfoBuilder.Build(_console, componentBuild); } else { _console.Out.WriteLine("=====Exiting: Build directory does not exist: " + componentBuild); } return; } _cmdOptions.App.ShowHelp(); _urls = new List <string>() { $"http://*:{HostingHelper.GetHostingPort()}" }; await Task.Run(() => { var contentRoot = Directory.GetCurrentDirectory(); #if RELEASE contentRoot = PathUtility.GetRootPath(true); #endif var hostBuilder = new WebHostBuilder() .UseKestrel(options => options.AddServerHeader = false) .UseContentRoot(contentRoot) .UseUrls(_urls.ToArray()) .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((webHostBuilderContext, logging) => { IConfiguration configuration = webHostBuilderContext.Configuration; ILoggingBuilder loggerBuilder = logging; loggerBuilder.AddConfiguration(configuration.GetSection("Logging")); loggerBuilder.AddConsole(); loggerBuilder.AddDebug(); }) .UseStartup <Startup>(); #if RELEASE hostBuilder.UseWebRoot(PathUtility.GetRootPath()); #endif bool serveStatic = !string.IsNullOrEmpty(HostingHelper.StaticServe); if (serveStatic) { hostBuilder.UseWebRoot(HostingHelper.StaticServe); } var host = hostBuilder.Build(); if (!serveStatic) { var applicationLifetime = host.Services.GetService <IApplicationLifetime>(); applicationLifetime.ApplicationStarted.Register(ApplicationStarted); } host.Run(); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure( IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime, IOptions <ExternalLinks> externalLinks, IOptions <CdnConfig> cdnConfig, ILogger <Startup> logger) { var instance = HostingHelper.GetWebsiteInstanceId(); applicationLifetime.ApplicationStarted.Register(() => logger.LogInformation($"Host fully started: ({instance})")); applicationLifetime.ApplicationStopping.Register(() => logger.LogInformation($"Host shutting down...waiting to complete requests: ({instance})")); applicationLifetime.ApplicationStopped.Register(() => logger.LogInformation($"Host fully stopped. All requests processed: ({instance})")); app.UseStatusCodePagesWithReExecute("/error/{0}"); if (env.IsDevelopment()) { var configuration = app.ApplicationServices.GetService <Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration>(); configuration.DisableTelemetry = true; app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // Add Content Security Policy app.UseCsp(options => options .DefaultSources(s => s.Self()) .StyleSources(s => { s.Self() .CustomSources("https://www.googletagmanager.com/", "https://www.tagmanager.google.com/", "https://tagmanager.google.com/", "https://fonts.googleapis.com/", cdnConfig.Value.Url.AbsoluteUri); } ) .ScriptSources(s => { s.UnsafeInlineSrc = true; s.UnsafeEvalSrc = true; s.Self() .CustomSources("https://az416426.vo.msecnd.net", "https://www.google-analytics.com/analytics.js", "https://www.googletagmanager.com/", "https://www.tagmanager.google.com/", "https://tagmanager.google.com/", "https://ajax.googleapis.com/", cdnConfig.Value.Url.AbsoluteUri); } ) .FontSources(s => s.Self() .CustomSources("data:", "https://fonts.googleapis.com/", cdnConfig.Value.Url.AbsoluteUri) ) .ConnectSources(s => s.Self() .CustomSources("https://dc.services.visualstudio.com") ) .ImageSources(s => s.Self() .CustomSources("https://maps.googleapis.com", "https://www.google-analytics.com", "https://ssl.gstatic.com", "https://www.gstatic.com/", "data:", cdnConfig.Value.Url.AbsoluteUri) ) .ReportUris(r => r.Uris("/ContentPolicyReport/Report"))); //Registered before static files to always set header app.UseXContentTypeOptions(); app.UseReferrerPolicy(opts => opts.NoReferrer()); app.UseXXssProtection(opts => opts.EnabledWithBlockMode()); app.UseAuthentication(); app.UseHealthChecks("/health", new HealthCheckOptions { ResponseWriter = HealthCheckResponseWriter.WriteJsonResponse }); app.UseStaticFiles(); app.UseCookiePolicy(); //Registered after static files, to set headers for dynamic content. app.UseXfo(xfo => xfo.Deny()); app.UseXDownloadOptions(); app.UseXRobotsTag(options => options.NoIndex().NoFollow()); app.UseRedirectValidation(opts => { opts.AllowSameHostRedirectsToHttps(); opts.AllowedDestinations(GetAllowableDestinations(_authConfig, externalLinks.Value)); }); //Register this earlier if there's middleware that might redirect. app.UseNoCacheHttpHeaders(); // Effectively forces the browser to always request dynamic pages app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); }