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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                WorkerCount = 1
            });

            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new[] { new HangfireDashboardAuthorizationFilter() }
            });

            GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute {
                Attempts = 0
            });
            HangfireJobScheduler.SchedulerReccuringJobs();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 2
0
        public static void AddHangfire(this IApplicationBuilder app, IConfiguration configuration)
        {
            var showDashboard = configuration.GetValue <bool?>("Hangfire:ShowDashboard");
            var dashboardUrl  = configuration.GetValue <string>("Hangfire:Url");

            if (showDashboard == null)
            {
                throw new ArgumentNullException("Invalid hangfire showDashboard configurations, check appsettings.json");
            }
            if (dashboardUrl == null)
            {
                throw new ArgumentNullException("Invalid hangfire url, check appsettings.json");
            }

            if (!dashboardUrl.StartsWith("/"))
            {
                dashboardUrl = $"/{dashboardUrl}";
            }

            app.UseHangfireDashboard(dashboardUrl, new DashboardOptions
            {
                IsReadOnlyFunc = context => !showDashboard.Value
            });

            app.UseHangfireServer();

            HangfireJobScheduler.ScheduleRecurringJobs();
        }
Ejemplo n.º 3
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseOpenApi();
            app.UseSwaggerUi3();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // hangfire
            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new[] { new HangfireDashboardAuthorizationFilter() }
            });
            app.UseHangfireServer();
            HangfireJobScheduler.ScheduleRecurringJob();
        }
Ejemplo n.º 4
0
        // 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();
            }
            app.UseRouting();

            app.UseCors("MyAllowSpecificOrigins");

            app.UseHangfireDashboard();

            app.UseHttpsRedirection();



            app.UseAuthentication();

            app.UseAuthorization();

            app.UseMiddleware(typeof(ErrorHandlingMiddleware));

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });



            // Schedule all background jobs.
            HangfireJobScheduler.ScheduleRecurringJobs();
        }
Ejemplo n.º 5
0
        private void ConfigureHangfire(IApplicationBuilder app)
        {
            if (!Configuration.GetValue <bool>(Constants.HangfireEnabled))
            {
                return;
            }

            var dashboardOptions = new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthorisationFilter(GetAdminRoleName()) },
                DisplayStorageConnectionString = false,
                // Added to squash intermittent 'The required antiforgery cookie token must be provided' exceptions
                // Does not pose a significant attack vector as all jobs are essentially idempotent.
                IgnoreAntiforgeryToken = true
            };

            app.UseHangfireDashboard("/hangfire", dashboardOptions);
            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                WorkerCount = Configuration.GetValue <int>(Constants.HangfireWorkerCount)
            });
            GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute {
                Attempts = 0
            });

            var scheduledJobConfig = new ScheduledJobsConfig();

            Configuration.GetSection(Constants.ScheduledJobsConfig).Bind(scheduledJobConfig);
            HangfireJobScheduler.ScheduleRecurringJobs(scheduledJobConfig);
        }
Ejemplo n.º 6
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                if (env.EnvironmentName == GlobalConstants.ENV_PRODUCTION)
                {
                   #warning Note that this API is mutually exclusive with DbContext.Database.EnsureCreated(). EnsureCreated does not use migrations to create the database and therefore the database that is created cannot be later updated using migrations.
                    this.ApplyMigrations(dbContext);
                }

                new ApplicationDbContextSeeder().SeedAsync(dbContext, serviceScope.ServiceProvider).GetAwaiter().GetResult();
            }

            if (env.EnvironmentName == "Development")
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseStaticFiles();
            app.UseCookiePolicy();

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

            app.UseHangfireServer();
            app.UseHangfireDashboard("/Administration/hangfire", new DashboardOptions()
            {
                DisplayStorageConnectionString = true,
                Authorization = new[] { new DashboardAuthorizationFilter() }
            });

            HangfireJobScheduler.ScheduleRecurringJobs();

            app.UseNotificationHandlerMiddleware();
            app.UseCustomExceptionHandlerMiddleware();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub <UserNotificationHub>("/userNotificationHub");
                endpoints.MapRazorPages();
                endpoints.MapAreaControllerRoute(
                    name: "admin",
                    areaName: "Administration",
                    pattern: "Administration/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    private static void ConfigureHangfire(WebApplication app)
    {
        if (!app.Configuration.GetValue <bool>(Constants.HangfireEnabled))
        {
            return;
        }

        var dashboardOptions = new DashboardOptions
        {
            Authorization =
                new[] { new HangfireAuthorisationFilter(app.Configuration.GetSection("AdOptions")["AdminUserGroup"]) },
            DisplayStorageConnectionString = false,
        };

        app.UseHangfireDashboard("/hangfire", dashboardOptions);
        GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute {
            Attempts = 0
        });

        var scheduledJobConfig = new ScheduledJobsConfig();

        app.Configuration.GetSection(Constants.ScheduledJobsConfig).Bind(scheduledJobConfig);
        HangfireJobScheduler.ScheduleRecurringJobs(scheduledJobConfig);
    }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseDatabaseErrorPage();
            }
            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();
            }

            // Add this line; you'll need `using Serilog;` up the top, too
            app.UseSerilogRequestLogging();

            var supportedCultures = new string[] { "bg", "en" };

            app.UseRequestLocalization(options =>
                                       options
                                       .AddSupportedCultures(supportedCultures)
                                       .AddSupportedUICultures(supportedCultures)
                                       .SetDefaultCulture("bg")
                                       .RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context =>
            {
                string userLangs   = context.Request.Headers["Accept-Language"].ToString();
                string firstLang   = userLangs.Split(',').FirstOrDefault();
                string defaultLang = string.IsNullOrEmpty(firstLang) ? "bg" : firstLang;
                return(Task.FromResult(new ProviderCultureResult(defaultLang, defaultLang)));
            }))
                                       );

            //Hangfire
            app.UseHangfireServer(new BackgroundJobServerOptions()
            {
                WorkerCount = 1
            });
            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new IDashboardAuthorizationFilter[]
                {
                    new HangfireAuthorizationFilter()
                }
            });

            app.UseCors(options =>
            {
                options.AllowAnyHeader();
                options.AllowAnyMethod();
                options.AllowCredentials();
                options.WithOrigins(new string[]
                {
                    "http://localhost:8080",
                    "http://localhost:8080/#/",
                    "http://localhost:8082",
                    "http://localhost:8082/#"
                });
            });

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapHub <AuctionHub>("/auctions/hub");
            });

            CreateRoles(serviceProvider);

            GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute {
                Attempts = 1
            });
            HangfireJobScheduler.ScheduleRecurringJobs(app.ApplicationServices);
        }
Ejemplo n.º 9
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)
        {
            loggerFactory.AddNLog();


            app.UseCors(CorsPolicy.AllowAll);
            app.UseAuthentication();
            app.UseHttpsRedirection();

            // Return static files and end the pipeline.
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    // Cache static files for 30 days
                    ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=2592000");
                    ctx.Context.Response.Headers.Append("Expires", DateTime.UtcNow.AddDays(30).ToString("R", CultureInfo.InvariantCulture));
                }
            });

            app.UseErrorHandlingMiddleware();
            app.UseErrorLoggingMiddleware();

            //app.UseDeveloperExceptionPage();
            app.Use(async(ctx, next) =>
            {
                await next();

                if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
                {
                    //Re-execute the request so the user gets the error page
                    string originalPath       = ctx.Request.Path.Value;
                    ctx.Items["originalPath"] = originalPath;
                    ctx.Request.Path          = "/error/404";
                    await next();
                }
            });
            //app.UseStatusCodePagesWithReExecute("/error/500");
            app.UseExceptionHandler("/error/500");

            app.UseMvcWithDefaultRoute();

            //app.UseMvc();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
#if DEBUG
            app.ApplicationServices.GetService <smartFundsDatabaseInitializerToMigrate>().Init();
#endif

            var activeHangfire = Configuration.GetValue <bool>("HangfireConfig:Active") != null
                ? Configuration.GetValue <bool>("HangfireConfig:Active")
                : true;

            if (activeHangfire)
            {
                app.UseHangfireServer();
                app.UseHangfireDashboard();
                HangfireJobScheduler.ScheduleRecurringJobs();
            }
        }
Ejemplo n.º 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,
            ILoggerFactory factory)
        {
            // Configure how to display the errors and the level of severity
            if (env.IsEnvironment("Development"))
            {
                app.UseDeveloperExceptionPage();
                factory.AddDebug(LogLevel.Information);
            }
            else
            {
                app.UseHsts();
                factory.AddDebug(LogLevel.Error);
            }

            if (!env.IsEnvironment("Testing"))
            {
                factory.AddDebug(LogLevel.Information);
                app.UseSwagger();
            }
            else
            {
                factory.AddConsole();
            }


            app.UseCors("MyPolicy");

            app.UseStaticFiles();
            app.UseHttpsRedirection();
            app.UseAuthentication();

            app.Use((context, next) =>
            {
                context.Response.Headers["Access-Control-Expose-Headers"]    = "origin, content-type, accept, authorization, ETag, if-none-match";
                context.Response.Headers["Access-Control-Max-Age"]           = "1209600";
                context.Response.Headers["Access-Control-Allow-Methods"]     = "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH";
                context.Response.Headers["Access-Control-Allow-Credentials"] = "true";
                context.Response.Headers["Access-Control-Allow-Headers"]     = "origin, content-type, accept, authorization, Etag, if-none-match";
                context.Response.Headers["Access-Control-Allow-Origin"]      = "*";
                context.Response.Headers["X-XSS-Protection"]          = "1; mode=block";
                context.Response.Headers["X-Frame-Options"]           = "deny";
                context.Response.Headers["Strict-Transport-Security"] = "max-age=300; includeSubDomains";
                return(next.Invoke());
            });

            app.UseResponseCompression();
            app.UseHealthChecks("/health");

            app.UseMvc(
                config =>
            {
                config.MapRoute(
                    "Default",
                    "{controller}/{action}/{id?}",
                    new { controller = "Home", action = "index" });
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint.


            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Seed .Net"); });

            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new[] { new HangFireAuthenticationFilter() }
            });

            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                WorkerCount = 1,
            });

            GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute {
                Attempts = 0
            });
            HangfireJobScheduler.ScheduleRecurringJobs();
        }
Ejemplo n.º 11
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)
        {
            env.ConfigureNLog("Nlog.config");

            loggerFactory.AddStackify();                     //add the provider
            app.ConfigureStackifyLogging(ConfigurationRoot); //configure settings and ASP.NET exception hooks

            if (env.IsDevelopment())
            {
                //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.UseDeveloperExceptionPage();
            }
            app.UseAuthentication();
            //add NLog to ASP.NET Core
            loggerFactory.AddNLog();
            app.UseMiddleware(typeof(AuthMiddleware));
            app.UseCors(x => x
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());
            app.UseExceptionHandler(builder =>
            {
                builder.Run(
                    async context =>
                {
                    var error     = context.Features.Get <IExceptionHandlerFeature>();
                    var exception = error.Error;

                    var logger = context.RequestServices.GetService <ILoggerService>();
                    logger.Error(exception);

                    var result = GlobalExceptionFilter.GetStatusCode <object>(exception);
                    context.Response.StatusCode  = (int)result.statusCode;
                    context.Response.ContentType = "application/json";

                    var responseJson = JsonConvert.SerializeObject(result.responseModel, new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });
                    await context.Response.WriteAsync(responseJson);
                });
            });
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            //This line enables the app to use Swagger, with the configuration in the ConfigureServices method.
            app.UseSwagger();
            //This line enables Swagger UI, which provides us with a nice, simple UI with which we can view our API calls.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "RECODE API");
                c.RoutePrefix = string.Empty;
            });
            app.UseMvc();
            app.UseAuthentication();
            //The following line is also optional, if you required to monitor your jobs.
            //Make sure you're adding required authentication
            app.UseHangfireDashboard();
            //app.UseHangfireDashboard("/appHangfire", new DashboardOptions
            //{
            //   Authorization= new[] {new HangfireDasnBoardAuthorizationFilter()}
            //});
            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                WorkerCount = 1,
            });
            GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute {
                Attempts = 5
            });
            HangfireJobScheduler.SchedulerRecurringJobs();
        }