Exemple #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)
        {
            loggerFactory.AddConsole(_configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    ConfigFile = "./webpack.config.js"
                });
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            var options = new RewriteOptions();

            options.AddRedirectToHttps();

            async Task <Context> BuildUserContext(HttpContext c)
            {
                var userManager = app.ApplicationServices.GetRequiredService <UserManager <ApplicationUser> >();
                var currentUser = await userManager.GetUserAsync(c.User);

                return(new Context
                {
                    CurrentUser = currentUser,
                    HttpContext = c
                });
            }

            app.UseRewriter(options);
            app.UseHangfireServer();
            app.UseHangfireDashboard();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseSession();
            app.UseWebSockets();
            app.UseGraphQLWebSocket <AppSchema>(new GraphQLWebSocketsOptions());
            app.UseGraphQLHttp <AppSchema>(new GraphQLHttpOptions()
            {
                BuildUserContext = BuildUserContext
            });

            RecurringJob.AddOrUpdate <IGenreService>(x => x.UpdateCoverImages(), Cron.Daily);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    "app",
                    "{controller}/{action}"
                    );

                routes.MapRoute(
                    "externalLoginCallback",
                    "Account/externalLoginCallback/{returnUrl}"
                    );

                routes.MapSpaFallbackRoute(
                    "default",
                    new
                {
                    controller = "App",
                    action     = "Index"
                }
                    );
            });
        }
Exemple #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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/error/500");
                app.UseHsts();
            }
            //Do not write telemetry to debug output
            TelemetryDebugWriter.IsTracingDisabled = true;

            app.UseResponseCaching();

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();
            //WorkContextBuildMiddleware must  always be registered first in  the Middleware chain
            app.UseMiddleware <WorkContextBuildMiddleware>();
            app.UseMiddleware <StoreMaintenanceMiddleware>();
            app.UseMiddleware <NoLiquidThemeMiddleware>();
            app.UseMiddleware <CreateStorefrontRolesMiddleware>();
            app.UseMiddleware <ApiErrorHandlingMiddleware>();


            app.UseStatusCodePagesWithReExecute("/error/{0}");

            var rewriteOptions = new RewriteOptions();

            //Load IIS url rewrite rules from external file
            if (File.Exists("IISUrlRewrite.xml"))
            {
                using (var iisUrlRewriteStreamReader = File.OpenText("IISUrlRewrite.xml"))
                {
                    rewriteOptions.AddIISUrlRewrite(iisUrlRewriteStreamReader);
                }
            }
            rewriteOptions.Add(new StorefrontUrlNormalizeRule());

            var requireHttpsOptions = new RequireHttpsOptions();

            Configuration.GetSection("VirtoCommerce:RequireHttps").Bind(requireHttpsOptions);
            if (requireHttpsOptions.Enabled)
            {
                rewriteOptions.AddRedirectToHttps(requireHttpsOptions.StatusCode, requireHttpsOptions.Port);
            }
            app.UseRewriter(rewriteOptions);
            //Enable browser XSS protection
            app.Use(async(context, next) =>
            {
                context.Response.Headers["X-Xss-Protection"] = "1";
                await next();
            });
            app.UseMvc(routes =>
            {
                routes.MapSlugRoute("{*path}", defaults: new { controller = "Home", action = "Index" });
            });
        }
Exemple #3
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.AddConsole(_configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    ConfigFile = "./webpack.config.js",
                });
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }


            Context BuildUserContext(HttpContext c)
            {
                return(new Context
                {
                    HttpContext = c
                });
            }

            var options = new RewriteOptions();

            if (!_env.IsDevelopment())
            {
                options.AddRedirectToHttps();
            }
            app.UseRewriter(options);
            app.UseStaticFiles();
            app.UseSession();
            app.UseGraphQLHttp <AppSchema>(new GraphQLHttpOptions
            {
                ExposeExceptions = !env.IsProduction(),
                BuildUserContext = BuildUserContext,
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    "constants",
                    "constants.js",
                    new
                {
                    controller = "App",
                    action     = "GetJavaScript",
                }
                    );

                routes.MapRoute(
                    "app",
                    "{action}",
                    new
                {
                    controller = "App",
                }
                    );

                routes.MapSpaFallbackRoute(
                    "default",
                    new
                {
                    controller = "App",
                    action     = "Index"
                }
                    );
            });
        }
Exemple #4
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseStatusCodePages("text/plain", "Status code page, status code: {0}");
            }

            app.UseStatusCodePagesWithReExecute("/error/{0}");

            app.UseMiddleware <WebMarkupMinFileNotFoundHandlerMiddleware>();

            app.UseResponseCompression();

            app.UseWebOptimizer();

            app.UseMiddleware <ArinMiddleware>();

            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = (context) =>
                {
                    var time = TimeSpan.FromDays(365);
                    context.Context.Response.Headers[HeaderNames.CacheControl] = $"max-age={time.TotalSeconds}";
                    context.Context.Response.Headers[HeaderNames.Expires]      = DateTime.UtcNow.Add(time).ToString("R");
                }
            });

            var rewriter = new RewriteOptions();

            if (Configuration.GetValue <bool>("forcessl"))
            {
                rewriter.AddRedirectToHttps();
            }

            if (Configuration.GetValue <bool>("dropwww"))
            {
                rewriter.Add(new StripWwwRule());
            }

            var azWebRedirect = Configuration.GetValue <string>("redirectazweb");

            if (!string.IsNullOrWhiteSpace(azWebRedirect))
            {
                rewriter.Add(new RedirectAzWebRule(azWebRedirect));
            }

            if (rewriter.Rules.Count > 0)
            {
                app.UseRewriter(rewriter);
            }

            app.UseAuthentication();

            app.UseOutputCaching();
            app.UseWebMarkupMin();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Blog}/{action=Index}/{id?}"
                    );
            });
        }
Exemple #5
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())
            {
                // Only use Console and Debug logging during development.
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();

                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                //app.UseExceptionHandler("/Home/Error");
                app.UseDeveloperExceptionPage();
                if (HasProjectId)
                {
                    // Send logs to Stackdriver Logging.
                    loggerFactory.AddGoogle(ProjectId);
                    // Sends logs to Stackdriver Error Reporting.
                    app.UseGoogleExceptionLogging();
                    // Sends logs to Stackdriver Trace.
                    app.UseGoogleTrace();

                    var startupLogger = loggerFactory.CreateLogger <Startup>();
                    startupLogger.LogInformation(
                        "Stackdriver Logging enabled: https://console.cloud.google.com/logs/");
                    startupLogger.LogInformation(
                        "Stackdriver Error Reporting enabled: https://console.cloud.google.com/errors/");
                    startupLogger.LogInformation(
                        "Stackdriver Trace not enabled: https://console.cloud.google.com/traces/");
                }
                else
                {
                    var startupLogger = loggerFactory.CreateLogger <Startup>();
                    startupLogger.LogWarning(
                        "Stackdriver Logging not enabled. Missing Google:ProjectId in configuration.");
                    startupLogger.LogWarning(
                        "Stackdriver Error Reporting not enabled. Missing Google:ProjectId in configuration.");
                    startupLogger.LogWarning(
                        "Stackdriver Trace not enabled. Missing Google:ProjectId in configuration.");
                }
            }

            var rewriteOptions = new RewriteOptions();

            if (!env.IsDevelopment())
            {
                rewriteOptions.Add(new RewriteHttpsOnAppEngine(HttpsPolicy.Required));
            }
            else
            {
                rewriteOptions.AddRedirectToHttps(302, 44393);
            }
            app.UseRewriter(rewriteOptions);

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseResponseCompression();

            app.Use(async(context, next) =>
            {
                context.Response.Headers.Add("X-Frame-Options", "DENY");
                await next();
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/error/500");
                app.UseHsts();
            }
            // Do not write telemetry to debug output
            TelemetryDebugWriter.IsTracingDisabled = true;

            app.UseResponseCaching();

            app.UseResponseCompression();

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();
            // WorkContextBuildMiddleware must  always be registered first in  the Middleware chain
            app.UseMiddleware <WorkContextBuildMiddleware>();
            app.UseMiddleware <StoreMaintenanceMiddleware>();
            app.UseMiddleware <NoLiquidThemeMiddleware>();
            app.UseMiddleware <CreateStorefrontRolesMiddleware>();
            app.UseMiddleware <ApiErrorHandlingMiddleware>();

            var mvcJsonOptions = app.ApplicationServices.GetService <IOptions <MvcJsonOptions> >().Value;

            mvcJsonOptions.SerializerSettings.Converters.Add(new CartTypesJsonConverter(app.ApplicationServices.GetService <IWorkContextAccessor>()));
            mvcJsonOptions.SerializerSettings.Converters.Add(new MoneyJsonConverter(app.ApplicationServices.GetService <IWorkContextAccessor>()));
            mvcJsonOptions.SerializerSettings.Converters.Add(new CurrencyJsonConverter(app.ApplicationServices.GetService <IWorkContextAccessor>()));
            mvcJsonOptions.SerializerSettings.Converters.Add(new OrderTypesJsonConverter(app.ApplicationServices.GetService <IWorkContextAccessor>()));
            mvcJsonOptions.SerializerSettings.Converters.Add(new RecommendationJsonConverter(app.ApplicationServices.GetService <IRecommendationProviderFactory>()));

            var mvcViewOptions = app.ApplicationServices.GetService <IOptions <MvcViewOptions> >().Value;

            mvcViewOptions.ViewEngines.Add(app.ApplicationServices.GetService <ILiquidViewEngine>());

            // Do not use status code pages for Api requests
            app.UseWhen(context => !context.Request.Path.IsApi(), appBuilder =>
            {
                appBuilder.UseStatusCodePagesWithReExecute("/error/{0}");
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger(c => c.RouteTemplate = "docs/{documentName}/docs.json");

            var rewriteOptions = new RewriteOptions();

            // Load IIS url rewrite rules from external file
            if (File.Exists("IISUrlRewrite.xml"))
            {
                using (var iisUrlRewriteStreamReader = File.OpenText("IISUrlRewrite.xml"))
                {
                    rewriteOptions.AddIISUrlRewrite(iisUrlRewriteStreamReader);
                }
            }

            rewriteOptions.Add(new StorefrontUrlNormalizeRule());

            var requireHttpsOptions = new RequireHttpsOptions();

            Configuration.GetSection("VirtoCommerce:RequireHttps").Bind(requireHttpsOptions);
            if (requireHttpsOptions.Enabled)
            {
                rewriteOptions.AddRedirectToHttps(requireHttpsOptions.StatusCode, requireHttpsOptions.Port);
            }
            app.UseRewriter(rewriteOptions);
            // Enable browser XSS protection
            app.Use(async(context, next) =>
            {
                context.Response.Headers["X-Xss-Protection"] = "1";
                await next();
            });
            app.UseMvc(routes =>
            {
                routes.MapSlugRoute("{*path}", defaults: new { controller = "Home", action = "Index" });
            });
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseForwardedHeaders();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/error/500");
                app.UseHsts();
            }
            // Do not write telemetry to debug output
            TelemetryDebugWriter.IsTracingDisabled = true;

            app.UseResponseCaching();

            app.UseResponseCompression();

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

            app.UseAuthentication();
            // WorkContextBuildMiddleware must  always be registered first in  the Middleware chain
            app.UseMiddleware <WorkContextBuildMiddleware>();
            app.UseMiddleware <StoreMaintenanceMiddleware>();
            app.UseMiddleware <NoLiquidThemeMiddleware>();
            app.UseMiddleware <CreateStorefrontRolesMiddleware>();
            app.UseMiddleware <ApiErrorHandlingMiddleware>();

            var mvcJsonOptions = app.ApplicationServices.GetService <IOptions <MvcNewtonsoftJsonOptions> >().Value;

            mvcJsonOptions.SerializerSettings.Converters.Add(new CartTypesJsonConverter(app.ApplicationServices.GetService <IWorkContextAccessor>()));
            mvcJsonOptions.SerializerSettings.Converters.Add(new MoneyJsonConverter(app.ApplicationServices.GetService <IWorkContextAccessor>()));
            mvcJsonOptions.SerializerSettings.Converters.Add(new CurrencyJsonConverter(app.ApplicationServices.GetService <IWorkContextAccessor>()));
            mvcJsonOptions.SerializerSettings.Converters.Add(new OrderTypesJsonConverter(app.ApplicationServices.GetService <IWorkContextAccessor>()));
            mvcJsonOptions.SerializerSettings.Converters.Add(new RecommendationJsonConverter(app.ApplicationServices.GetService <IRecommendationProviderFactory>()));

            var mvcViewOptions = app.ApplicationServices.GetService <IOptions <MvcViewOptions> >().Value;

            mvcViewOptions.ViewEngines.Add(app.ApplicationServices.GetService <ILiquidViewEngine>());

            // Do not use status code pages for Api requests
            app.UseWhen(context => !context.Request.Path.IsApi(), appBuilder =>
            {
                appBuilder.UseStatusCodePagesWithReExecute("/error/{0}");
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger(c => c.RouteTemplate = "docs/{documentName}/docs.json");

            var swaggerOptions = app.ApplicationServices.GetService <IOptions <SwaggerOptions> >().Value;

            if (swaggerOptions.UI.Enable)
            {
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint($"./{SwaggerDocName}/docs.json", SwaggerDocName);
                    c.RoutePrefix = "docs";
                    c.EnableValidator();
                    c.IndexStream = () =>
                    {
                        var type = typeof(Startup).GetTypeInfo().Assembly
                                   .GetManifestResourceStream("VirtoCommerce.Storefront.wwwroot.swagger.index.html");
                        return(type);
                    };
                    c.DocumentTitle = "VirtoCommerce Storefront REST API documentation";
                    c.InjectStylesheet("/swagger/vc.css");
                    c.ShowExtensions();
                    c.DocExpansion(DocExpansion.None);
                    c.DefaultModelsExpandDepth(-1);
                });
            }

            var rewriteOptions = new RewriteOptions();

            // Load IIS url rewrite rules from external file
            if (File.Exists("IISUrlRewrite.xml"))
            {
                using (var iisUrlRewriteStreamReader = File.OpenText("IISUrlRewrite.xml"))
                {
                    rewriteOptions.AddIISUrlRewrite(iisUrlRewriteStreamReader);
                }
            }

            rewriteOptions.Add(new StorefrontUrlNormalizeRule());

            var requireHttpsOptions = new RequireHttpsOptions();

            Configuration.GetSection("VirtoCommerce:RequireHttps").Bind(requireHttpsOptions);
            if (requireHttpsOptions.Enabled)
            {
                rewriteOptions.AddRedirectToHttps(requireHttpsOptions.StatusCode, requireHttpsOptions.Port);
            }
            app.UseRewriter(rewriteOptions);
            // Enable browser XSS protection
            app.Use(async(context, next) =>
            {
                context.Response.Headers["X-Xss-Protection"] = "1";
                await next();
            });


            // It will be good to rewrite endpoint routing as described here, but it's not easy to do:
            // https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#routing-startup-code

            app.UseMvc(routes =>
            {
                routes.MapSlugRoute("{*path}", defaults: new { controller = "Home", action = "Index" });
            });
        }
Exemple #8
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.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddGoogle(GetProjectId());
            loggerFactory.AddDebug();

            // Configure redirects to HTTPS.
            var rewriteOptions = new RewriteOptions();

            if (Configuration["IAmRunningInGoogleCloud"] == "true")
            {
                rewriteOptions.Add(new RewriteHttpsOnAppEngine(
                                       HttpsPolicy.Required));
            }
            else
            {
                rewriteOptions.AddRedirectToHttps(302, 44393);
            }
            app.UseRewriter(rewriteOptions);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseGoogleExceptionLogging();
                app.UseGoogleTrace();
            }

            app.UseStaticFiles();

            app.UseIdentity();

            int authenticationProviderCount = 0;
            // Add external authentication middleware below. To configure them
            // please see http://go.microsoft.com/fwlink/?LinkID=532715
            string googleClientId =
                Configuration["Authentication:Google:ClientId"];

            if (!string.IsNullOrWhiteSpace(googleClientId))
            {
                app.UseGoogleAuthentication(new GoogleOptions()
                {
                    ClientId     = googleClientId,
                    ClientSecret = Configuration[
                        "Authentication:Google:ClientSecret"],
                });
                authenticationProviderCount += 1;
            }

            string facebookAppId =
                Configuration["Authentication:Facebook:AppId"];

            if (!string.IsNullOrWhiteSpace(facebookAppId))
            {
                app.UseFacebookAuthentication(new FacebookOptions()
                {
                    AppId     = facebookAppId,
                    AppSecret = Configuration[
                        "Authentication:Facebook:AppSecret"],
                });
                authenticationProviderCount += 1;
            }

            if (0 == authenticationProviderCount)
            {
                app.Run(RequireAuthenticationProviderHandler);
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }