コード例 #1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var log = loggerFactory.CreateLogger("Startup");

            string connectionString = "unknown.";

            try
            {
                using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    log.LogInformation("Fetching the application's database context ...");
                    AppDbContext    context        = serviceScope.ServiceProvider.GetService <AppDbContext>();
                    IDynamicsClient dynamicsClient = serviceScope.ServiceProvider.GetService <IDynamicsClient>();

                    connectionString = context.Database.GetDbConnection().ConnectionString;

                    log.LogInformation("Migrating the database ...");
                    context.Database.Migrate();
                    log.LogInformation("The database migration complete.");

                    // run the database seeders
                    log.LogInformation("Adding/Updating seed data ...");

                    Seeders.SeedFactory <AppDbContext> seederFactory = new Seeders.SeedFactory <AppDbContext>(Configuration, env, loggerFactory, dynamicsClient);
                    seederFactory.Seed((AppDbContext)context);
                    log.LogInformation("Seeding operations are complete.");
                }
            }
            catch (Exception e)
            {
                StringBuilder msg = new StringBuilder();
                msg.AppendLine("The database migration failed!");
                msg.AppendLine("The database may not be available and the application will not function as expected.");
                msg.AppendLine("Please ensure a database is available and the connection string is correct.");
                msg.AppendLine("If you are running in a development environment, ensure your test database and server configuration match the project's default connection string.");
                msg.AppendLine("Which is: " + connectionString);
                log.LogCritical(new EventId(-1, "Database Migration Failed"), e, msg.ToString());
            }


            string pathBase = Configuration["BASE_PATH"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                app.UsePathBase(pathBase);
            }
            if (!env.IsProduction())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.Use(async(ctx, next) =>
            {
                ctx.Response.Headers.Add("Content-Security-Policy",
                                         "script-src 'self' 'unsafe-eval' 'unsafe-inline' https://apis.google.com https://maxcdn.bootstrapcdn.com https://cdnjs.cloudflare.com https://code.jquery.com https://stackpath.bootstrapcdn.com https://fonts.googleapis.com");
                ctx.Response.Headers.Add("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
                await next();
            });
            app.UseXContentTypeOptions();
            app.UseXfo(xfo => xfo.Deny());

            StaticFileOptions staticFileOptions = new StaticFileOptions();

            staticFileOptions.OnPrepareResponse = ctx =>
            {
                ctx.Context.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate, private";
                ctx.Context.Response.Headers[HeaderNames.Pragma]       = "no-cache";
                ctx.Context.Response.Headers["X-Frame-Options"]        = "SAMEORIGIN";
                ctx.Context.Response.Headers["X-XSS-Protection"]       = "1; mode=block";
                ctx.Context.Response.Headers["X-Content-Type-Options"] = "nosniff";
            };

            app.UseStaticFiles(staticFileOptions);
            app.UseSpaStaticFiles(staticFileOptions);
            app.UseXXssProtection(options => options.EnabledWithBlockMode());
            app.UseNoCacheHttpHeaders();
            // IMPORTANT: This session call MUST go before UseMvc()
            app.UseSession();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                // Only run the angular CLI Server in Development mode (not staging or test.)
                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

            // enable Splunk logger
            if (!string.IsNullOrEmpty(Configuration["SPLUNK_COLLECTOR_URL"]))
            {
                var splunkLoggerConfiguration = GetSplunkLoggerConfiguration(app);

                //Append Http Json logger
                loggerFactory.AddHECJsonSplunkLogger(splunkLoggerConfiguration);
            }
        }
コード例 #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            string pathBase = Configuration["BASE_PATH"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                app.UsePathBase(pathBase);
            }
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseXContentTypeOptions();
            app.UseXfo(xfo => xfo.Deny());
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseNoCacheHttpHeaders();
            // IMPORTANT: This session call MUST go before UseMvc()
            app.UseSession();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            var log = loggerFactory.CreateLogger("Startup");

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

            string connectionString = "unknown.";

            try
            {
                using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    log.LogInformation("Fetching the application's database context ...");
                    AppDbContext context = serviceScope.ServiceProvider.GetService <AppDbContext>();

                    IDistributedCache distributedCache = serviceScope.ServiceProvider.GetService <IDistributedCache>();
                    Gov.Lclb.Cllb.Public.Contexts.Microsoft.Dynamics.CRM.System system = serviceScope.ServiceProvider.GetService <Gov.Lclb.Cllb.Public.Contexts.Microsoft.Dynamics.CRM.System>();

                    connectionString = context.Database.GetDbConnection().ConnectionString;

                    log.LogInformation("Migrating the database ...");
                    context.Database.Migrate();
                    log.LogInformation("The database migration complete.");

                    // run the database seeders
                    log.LogInformation("Adding/Updating seed data ...");

                    Seeders.SeedFactory <AppDbContext> seederFactory = new Seeders.SeedFactory <AppDbContext>(Configuration, env, loggerFactory, system, distributedCache);
                    seederFactory.Seed((AppDbContext)context);
                    log.LogInformation("Seeding operations are complete.");
                }
            }
            catch (Exception e)
            {
                StringBuilder msg = new StringBuilder();
                msg.AppendLine("The database migration failed!");
                msg.AppendLine("The database may not be available and the application will not function as expected.");
                msg.AppendLine("Please ensure a database is available and the connection string is correct.");
                msg.AppendLine("If you are running in a development environment, ensure your test database and server configuration match the project's default connection string.");
                msg.AppendLine("Which is: " + connectionString);
                log.LogCritical(new EventId(-1, "Database Migration Failed"), e, msg.ToString());
            }
        }
コード例 #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            var log = loggerFactory.CreateLogger("Startup");

            string connectionString = "unknown.";

#if (USE_MSSQL)
            if (!string.IsNullOrEmpty(Configuration["DB_PASSWORD"]))
            {
                try
                {
                    using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
                    {
                        log.LogDebug("Fetching the application's database context ...");
                        AppDbContext    context        = serviceScope.ServiceProvider.GetService <AppDbContext>();
                        IDynamicsClient dynamicsClient = serviceScope.ServiceProvider.GetService <IDynamicsClient>();

                        connectionString = context.Database.GetDbConnection().ConnectionString;

                        log.LogDebug("Migrating the database ...");
                        context.Database.Migrate();
                        log.LogDebug("The database migration complete.");

                        // run the database seeders
                        log.LogDebug("Adding/Updating seed data ...");

                        Seeders.SeedFactory <AppDbContext> seederFactory = new Seeders.SeedFactory <AppDbContext>(Configuration, env, loggerFactory, dynamicsClient);
                        seederFactory.Seed((AppDbContext)context);
                        log.LogDebug("Seeding operations are complete.");
                    }
                }
                catch (Exception e)
                {
                    StringBuilder msg = new StringBuilder();
                    msg.AppendLine("The database migration failed!");
                    msg.AppendLine("The database may not be available and the application will not function as expected.");
                    msg.AppendLine("Please ensure a database is available and the connection string is correct.");
                    msg.AppendLine("If you are running in a development environment, ensure your test database and server configuration match the project's default connection string.");
                    msg.AppendLine("Which is: " + connectionString);
                    log.LogCritical(new EventId(-1, "Database Migration Failed"), e, msg.ToString());
                }
            }
#else
            // seed for newsletter.

            using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                log.LogDebug("Fetching the application's MS Dynamics interface ...");
                IDynamicsClient dynamicsClient = serviceScope.ServiceProvider.GetService <IDynamicsClient>();
                // run the database seeders
                log.LogDebug("Adding/Updating seed data ...");
                Seeders.SeedFactory <AppDbContext> seederFactory = new Seeders.SeedFactory <AppDbContext>(_configuration, env, loggerFactory, dynamicsClient);
                seederFactory.Seed(null);
                log.LogDebug("Seeding operations are complete.");
            }
#endif


            string pathBase = _configuration["BASE_PATH"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                app.UsePathBase(pathBase);
            }
            if (!env.IsProduction())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(errorApp =>
                {
                    errorApp.Run(async context =>
                    {
                        context.Response.StatusCode  = 500;
                        context.Response.ContentType = "text/html";

                        await context.Response.WriteAsync("An unexpected server error occurred.\r\n");

                        var exceptionHandlerPathFeature =
                            context.Features.Get <IExceptionHandlerPathFeature>();

                        if (exceptionHandlerPathFeature?.Error != null)
                        {
                            Log.Logger.Error(exceptionHandlerPathFeature?.Error, "Unexpected Error");
                        }
                    });
                });
                app.UseHsts(); // Strict-Transport-Security
                app.UseCors(MyAllowSpecificOrigins);
            }

            var healthCheckOptions = new HealthCheckOptions
            {
                ResponseWriter = async(c, r) =>
                {
                    c.Response.ContentType = MediaTypeNames.Application.Json;
                    var result = JsonConvert.SerializeObject(
                        new
                    {
                        checks = r.Entries.Select(e =>
                                                  new
                        {
                            description  = e.Key,
                            status       = e.Value.Status.ToString(),
                            responseTime = e.Value.Duration.TotalMilliseconds
                        }),
                        totalResponseTime = r.TotalDuration.TotalMilliseconds
                    });
                    await c.Response.WriteAsync(result);
                }
            };
            app.UseHealthChecks("/hc/ready", new HealthCheckOptions
            {
                Predicate      = _ => true,
                ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
            });

            app.UseHealthChecks("/hc/live", new HealthCheckOptions
            {
                // Exclude all checks and return a 200-Ok.
                Predicate = (_) => false
            });

            app.UseXContentTypeOptions();
            app.UseXfo(xfo => xfo.Deny());

            StaticFileOptions staticFileOptions = new StaticFileOptions();

            staticFileOptions.OnPrepareResponse = ctx =>
            {
                ctx.Context.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate, private";
                ctx.Context.Response.Headers[HeaderNames.Pragma]       = "no-cache";
                ctx.Context.Response.Headers["X-Frame-Options"]        = "SAMEORIGIN";
                ctx.Context.Response.Headers["X-XSS-Protection"]       = "1; mode=block";
                ctx.Context.Response.Headers["X-Content-Type-Options"] = "nosniff";
            };

            app.UseStaticFiles(staticFileOptions);

            app.UseSpaStaticFiles(staticFileOptions);
            app.UseXXssProtection(options => options.EnabledWithBlockMode());
            app.UseNoCacheHttpHeaders();
            // IMPORTANT: This session call MUST go before UseMvc()
            app.UseSession();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });



            // enable Splunk logger using Serilog
            if (!string.IsNullOrEmpty(_configuration["SPLUNK_COLLECTOR_URL"]) &&
                !string.IsNullOrEmpty(_configuration["SPLUNK_TOKEN"])
                )
            {
                Serilog.Sinks.Splunk.CustomFields fields = new Serilog.Sinks.Splunk.CustomFields();
                if (!string.IsNullOrEmpty(_configuration["SPLUNK_CHANNEL"]))
                {
                    fields.CustomFieldList.Add(new Serilog.Sinks.Splunk.CustomField("channel", _configuration["SPLUNK_CHANNEL"]));
                }
                var splunkUri       = new Uri(_configuration["SPLUNK_COLLECTOR_URL"]);
                var upperSplunkHost = splunkUri.Host?.ToUpperInvariant() ?? string.Empty;

                // Fix for bad SSL issues


                Log.Logger = new LoggerConfiguration()
                             .Enrich.FromLogContext()
                             .Enrich.WithExceptionDetails()
                             .WriteTo.Console()
                             .WriteTo.EventCollector(splunkHost: _configuration["SPLUNK_COLLECTOR_URL"],
                                                     sourceType: "manual", eventCollectorToken: _configuration["SPLUNK_TOKEN"],
                                                     restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information,
#pragma warning disable CA2000 // Dispose objects before losing scope
                                                     messageHandler: new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }
                }
#pragma warning restore CA2000 // Dispose objects before losing scope
                                                     )
                             .CreateLogger();

                Serilog.Debugging.SelfLog.Enable(Console.Error);

                Log.Logger.Information("CARLA Portal Container Started");
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .Enrich.FromLogContext()
                             .Enrich.WithExceptionDetails()
                             .WriteTo.Console()
                             .CreateLogger();
            }

            if (env.IsDevelopment())
            {
                app.UseSpa(spa =>
                {
                    // To learn more about options for serving an Angular SPA from ASP.NET Core,
                    // see https://go.microsoft.com/fwlink/?linkid=864501

                    spa.Options.SourcePath = "ClientApp";

                    // Only run the angular CLI Server in Development mode (not staging or test.)
                    if (env.IsDevelopment())
                    {
                        spa.UseAngularCliServer(npmScript: "start");
                    }
                });
            }
            else
            {
                Log.Logger.Information("Not enabling single page application hosting from Dotnet - using externally hosted static content.");
            }
        }
コード例 #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseXContentTypeOptions();
            app.UseXfo(xfo => xfo.Deny());
            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseNoCacheHttpHeaders();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

            ILogger log = loggerFactory.CreateLogger(typeof(Startup));

            try
            {
                using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    log.LogInformation("Fetching the application's database context ...");
                    DataAccess context = serviceScope.ServiceProvider.GetService <DataAccess>();
                    // run the database seeders
                    log.LogInformation("Adding/Updating seed data ...");
                    Seeders.SeedFactory <DataAccess> seederFactory = new Seeders.SeedFactory <DataAccess>(Configuration, env, loggerFactory);
                    seederFactory.Seed((DataAccess)context);
                    log.LogInformation("Seeding operations are complete.");
                }
            }
            catch (Exception e)
            {
                StringBuilder msg = new StringBuilder();
                msg.AppendLine("The database migration failed!");
                msg.AppendLine("The database may not be available and the application will not function as expected.");
                msg.AppendLine("Please ensure a database is available and the connection string is correct.");
                msg.AppendLine("If you are running in a development environment, ensure your test database and server configuraiotn match the project's default connection string.");
                log.LogCritical(new EventId(-1, "Database Migration Failed"), e, msg.ToString());
            }
        }