Exemplo n.º 1
0
        /// <summary>
        /// Configure the using of added middleware
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public void Configure(IApplicationBuilder application)
        {
            var serviceProvider   = application.ApplicationServices;
            var grandConfig       = serviceProvider.GetRequiredService <GrandConfig>();
            var urlRewriteOptions = new RewriteOptions();
            var rewriteOptions    = false;

            if (grandConfig.UseUrlRewrite)
            {
                if (File.Exists("App_Data/UrlRewrite.xml"))
                {
                    using (var streamReader = File.OpenText("App_Data/UrlRewrite.xml"))
                    {
                        rewriteOptions = true;
                        urlRewriteOptions.AddIISUrlRewrite(streamReader);
                    }
                }
            }
            if (grandConfig.UrlRewriteHttpsOptions)
            {
                rewriteOptions = true;
                urlRewriteOptions.AddRedirectToHttps(grandConfig.UrlRewriteHttpsOptionsStatusCode, grandConfig.UrlRewriteHttpsOptionsPort);
            }
            if (grandConfig.UrlRedirectToHttpsPermanent)
            {
                rewriteOptions = true;
                urlRewriteOptions.AddRedirectToHttpsPermanent();
            }
            if (rewriteOptions)
            {
                application.UseRewriter(urlRewriteOptions);
            }
        }
Exemplo 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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/error/500");
                app.UseHsts();
            }

            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 <AntiforgeryTokenMiddleware>();
            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.MapStorefrontRoutes();
            });
        }
Exemplo n.º 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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/error/500");
            }

            app.UseResponseCaching();

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMiddleware <WorkContextBuildMiddleware>();
            app.UseMiddleware <StoreMaintenanceMiddleware>();
            app.UseMiddleware <NoLiquidThemeMiddleware>();
            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);
            app.UseMvc(routes =>
            {
                routes.MapStorefrontRoutes();
            });

            app.UseStorefrontRoles();
        }
Exemplo 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)
        {
            #region URL 跳转

            var options = new RewriteOptions();
            options.AddRedirect("xcode/(.*)", "blog/$1")
            // 可以链式配置
            // .AddRedirect()
            // 可以重写
            .AddRewrite(@"test1/(\d+)", "test2/$1", true)
            // 配置 https
            .AddRedirectToHttps()
            ;

            // 根据配置文件 Apache
            using (StreamReader streamReader = File.OpenText(""))
            {
                options.AddApacheModRewrite(reader: streamReader);
            }

            // 根据配置文件 IIS
            using (StreamReader streamReader = File.OpenText(""))
            {
                options.AddIISUrlRewrite(reader: streamReader);
            }

            // 多种自定义添加方式
            options.Add(RedirectHelper.RedirectUrl);
            options.Add(new CustomerRule());


            app.UseRewriter(options);

            #endregion


            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); });
            });
        }
Exemplo n.º 5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AppDbContext db)
        {
            DefaultFilesOptions options = new DefaultFilesOptions();

            options.DefaultFileNames.Clear();
            options.DefaultFileNames.Add("index.html");
            app.UseDefaultFiles(options);
            app.UseStaticFiles();

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

            //db.Database.EnsureDeleted();
            db.Database.EnsureCreated();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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



            //app.UseRewriter(new RewriteOptions().AddRewrite("app/(.*)", "app/$1",true).AddRewrite("AngularViews/(.*)", "AngularViews/$1",true).AddRewrite("(.*)", "/",true));

            using (StreamReader iisUrlRewriteReader = File.OpenText("ReWrite.xml"))
            {
                var rules = new RewriteOptions();

                rules.AddIISUrlRewrite(iisUrlRewriteReader);

                app.UseRewriter(rules);
            }
            app.UseFileServer();
        }
Exemplo n.º 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)
        {
            //重写中间件演示
            //var option = new RewriteOptions();
            //option.AddRedirect(@"xcode/(\d+)", "blog/$1")
            //    .AddRewrite(@"baidu/([a-z]{2,3})", "blog/$1", true)
            //    .AddRedirectToHttps();

            //app.UseRewriter(option);

            #region 使用配置文件设置重定向和重写规则

            var option = new RewriteOptions();
            //使用Apache配置文件
            using (StreamReader reader = File.OpenText("ApacheConfig.txt"))
            {
                option.AddApacheModRewrite(reader);
            }
            //使用IIS配置文件
            using (StreamReader reader = File.OpenText("IISUrlRewrite.xml"))
            {
                option.AddIISUrlRewrite(reader);
            }
            //使用委托
            option.Add(RewriteHelper.RedirectUrl);
            option.Add(RewriteHelper.RewriteUrl);
            //使用接口
            //option.Add(new CustomRule());

            app.UseRewriter(option);

            #endregion

            app.Run(async(context) =>
            {
                var url = context.Request.Protocol + context.Request.Host + context.Request.Path;
                await context.Response.WriteAsync("Hello World! " + url);
            });
        }
Exemplo n.º 7
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>();


            app.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" });
            });
        }
Exemplo n.º 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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseSession();
            //app.UseStaticFiles();
            //https://andrewlock.net/adding-cache-control-headers-to-static-files-in-asp-net-core/
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    const int durationInSeconds = 60 * 60 * 240;
                    ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                        "public,max-age=" + durationInSeconds;
                    var file  = ctx.File.PhysicalPath;
                    var file2 = ctx.File.Name;
                    // filter by js or css
                    ctx.Context.Response.Headers[HeaderNames.Vary] = "Accept-Encoding";
                }
            });

            app.UseAuthentication();

            app.UseWebMarkupMin();

            RewriteOptions ro = new RewriteOptions();

            var cd = Environment.MachineName;

            if (!cd.ToUpperInvariant().Contains("YORDAN".ToUpperInvariant()))
            {
                ro.AddRedirectToHttps();
            }

            ro.AddIISUrlRewrite(env.ContentRootFileProvider, "web.config");

            app.UseRewriter(ro);

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

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

            // Configure Kendo UI
            app.UseKendo(env);

            Utils.PopulateHungarianMappingDictionaries(env.WebRootPath);
            Utils.PopulateSerbianMappingDictionaries(env.WebRootPath);
            Utils.PopulateCroatianMappingDictionaries(env.WebRootPath);
        }
Exemplo n.º 9
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();
            }
            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 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" });
            });
        }
Exemplo n.º 10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseStatusCodePagesWithReExecute("/errors/{0}");

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(a =>
                {
                    a.Run(ctx =>
                    {
                        ctx.Response.StatusCode = StatusCodes.Status500InternalServerError;
                        return(Task.CompletedTask);
                    });
                });
            }

            using (StreamReader iisUrlRewriteStreamReader = File.OpenText("spa-url-rewrite.xml"))
            {
                RewriteOptions options = new RewriteOptions();
                options.AddRewrite(@"^assets/fonts/(.*)", "app/assets/fonts/$1", false);
                options.AddRewrite("^app$", "app/index.html", true);
                options.AddIISUrlRewrite(iisUrlRewriteStreamReader, true);

                app.UseRewriter(options);
            }

            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = ctx =>
                {
                    ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=3600");
                }
            });

            app.UseRouting();

            if (_authenticationEnabled)
            {
                app.UseAuthentication();
                app.UseAuthorization();
                app.UseMiddleware <SkillsCheckMiddleware>();
                app.UseMiddleware <LoggedInMiddleware>();
            }

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                endpoints.MapHub <Notifications>("/api/notifications");
            });

            if (IsSwaggerEnabled())
            {
                app.UseSwagger();
                app.UseSwaggerUI(
                    options =>
                {
                    options.SwaggerEndpoint("/swagger/v1/swagger.json", "Calculations Funding Frontend API");
                    options.DocumentTitle = "Calculations Funding - Swagger";
                });
            }
        }