Ejemplo n.º 1
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,
            ImperaContext dbContext,
            DbSeed dbSeed)
        {
            if (env.IsDevelopment())
            {
                app.UsePathBase("/api");
            }

            NLog.LogManager.Configuration.Variables["configDir"] = Configuration["LogDir"];

            //if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }

            // Enable Cors
            app.UseCors(b => b
                        .WithOrigins("http://localhost:8080", "https://dev.imperaonline.de", "https://imperaonline.de", "https://www.imperaonline.de")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .WithExposedHeaders("X-MiniProfiler-Ids")
                        .AllowCredentials());

            // Auth
            app.UseAuthentication();

            // TODO: Fix, how does this work?
            //app.UseOpenIddict();

            // Enable serving client and static assets
            app.UseResponseCompression();
            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    // Do not cache main entry point.
                    if (!ctx.File.Name.Contains("index.html"))
                    {
                        ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=6000000");
                    }
                }
            });

            app.UseMiniProfiler();

            // Configure swagger generation & UI
            app.UseOpenApi();
            app.UseSwaggerUi3();

            app.UseMvc(routes =>
            {
                // Route for sub areas, i.e. Admin
                routes.MapRoute("areaRoute", "{area:exists}/{controller=News}/{action=Index}");

                routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseWebSockets();
            app.UseSignalR(routes =>
            {
                routes.MapHub <Hubs.MessagingHub>("/signalr/chat");
                routes.MapHub <Hubs.GameHub>("/signalr/game");
            });

            // Initialize database
            Log.Info("Initializing database...").Write();
            if (env.IsDevelopment())
            {
                if (Startup.RunningUnderTest)
                {
                    dbContext.Database.EnsureDeleted();
                }
                else
                {
                    dbContext.Database.Migrate();
                }
            }
            else
            {
                Log.Info("Starting migration...").Write();
                dbContext.Database.Migrate();
                Log.Info("...done.").Write();
            }
            Log.Info("...done.").Write();

            Log.Info("Seeding database...").Write();
            dbSeed.Seed(dbContext).Wait();
            Log.Info("...done.").Write();

            // Hangfire
            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                Queues                  = new[] { JobQueues.Critical, JobQueues.Normal },
                WorkerCount             = 2,
                SchedulePollingInterval = TimeSpan.FromSeconds(30),
                ServerCheckInterval     = TimeSpan.FromSeconds(60),
                HeartbeatInterval       = TimeSpan.FromSeconds(60)
            });
            app.UseHangfireDashboard("/Admin/Hangfire", new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            });

            Hangfire.Common.JobHelper.SetSerializerSettings(new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.All
            });

            // Configure Impera background jobs
            JobConfig.Configure();
        }
Ejemplo n.º 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,
            ImperaContext dbContext,
            DbSeed dbSeed)
        {
            loggerFactory.AddNLog();
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.AddNLogWeb();
            NLog.LogManager.Configuration.Variables["configDir"] = Configuration["LogDir"];

            //if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }

            // Enable Cors
            app.UseCors(b => b
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .WithExposedHeaders("X-MiniProfiler-Ids")
                        .DisallowCredentials()
                        .Build());

            // Auth
            app.UseIdentity();

            /*app.UseFacebookAuthentication(new FacebookOptions
             * {
             *  AppId = Configuration["Authentication:Facebook:AppId"],
             *  AppSecret = Configuration["Authentication:Facebook:AppSecret"]
             * });
             *
             * app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions
             * {
             *  ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"],
             *  ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]
             * });*/

            app.UseOAuthValidation(options =>
            {
                options.Events = new AspNet.Security.OAuth.Validation.OAuthValidationEvents
                {
                    // Note: for SignalR connections, the default Authorization header does not work,
                    // because the WebSockets JS API doesn't allow setting custom parameters.
                    // To work around this limitation, the access token is retrieved from the query string.
                    OnRetrieveToken = context =>
                    {
                        context.Token = context.Request.Query["bearer_token"];

                        if (string.IsNullOrEmpty(context.Token))
                        {
                            context.Token = context.Request.Cookies["bearer_token"];
                        }

                        return(Task.FromResult(0));
                    }
                };
            });
            app.UseOpenIddict();

            // Enable serving client and static assets
            app.UseResponseCompression();
            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    // Do not cache main entry point.
                    if (!ctx.File.Name.Contains("index.html"))
                    {
                        ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=6000000");
                    }
                }
            });

            app.UseMiniProfiler(new StackExchange.Profiling.MiniProfilerOptions
            {
                RouteBasePath = "~/admin/profiler",

                SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(),

                // Control storage
                Storage = new MemoryCacheStorage(TimeSpan.FromMinutes(60))
            });

            app.UseMvc(routes =>
            {
                // Route for sub areas, i.e. Admin
                routes.MapRoute("areaRoute", "{area:exists}/{controller=News}/{action=Index}");

                routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseWebSockets();
            app.UseSignalR();

            app.UseSwagger();
            app.UseSwaggerUi();

            // Initialize database
            Log.Info("Initializing database...").Write();
            if (env.IsDevelopment())
            {
                if (Startup.RunningUnderTest)
                {
                    dbContext.Database.EnsureDeleted();
                }

                dbContext.Database.Migrate();
            }
            else
            {
                Log.Info("Starting migration...").Write();
                dbContext.Database.Migrate();
                Log.Info("...done.").Write();
            }
            Log.Info("...done.").Write();

            Log.Info("Seeding database...").Write();
            dbSeed.Seed(dbContext).Wait();
            Log.Info("...done.").Write();

            AutoMapperConfig.Configure();

            // Hangfire
            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                Queues                  = new[] { JobQueues.Critical, JobQueues.Normal },
                WorkerCount             = 2,
                SchedulePollingInterval = TimeSpan.FromSeconds(30),
                ServerCheckInterval     = TimeSpan.FromSeconds(60),
                HeartbeatInterval       = TimeSpan.FromSeconds(60)
            });
            app.UseHangfireDashboard("/Admin/Hangfire", new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            });

            Hangfire.Common.JobHelper.SetSerializerSettings(new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.All
            });

            // Configure Impera background jobs
            JobConfig.Configure();
        }