Ejemplo n.º 1
0
    internal static void ConfigureSwashbuckle(IApplicationBuilder app)
    {
        var hostingEnvironment = app.ApplicationServices.GetRequiredService <IHostEnvironment>();

        var rewriterOptions = new RewriteOptions();

        if (hostingEnvironment.IsDevelopment())
        {
            // Configure rules for Swagger UI
            // redirect from 'docs' to 'docs/'
            rewriterOptions.AddRedirect($"^{UIPath}$", $"{UIPath}/");
            // rewrite 'docs/' to 'docs/index.html'
            rewriterOptions.AddRewrite($"^{UIPath}/$", $"{UIPath}/index.html", skipRemainingRules: false);
            // rewrite 'docs/*' to 'swagger/*'
            rewriterOptions.AddRewrite($"^{UIPath}/(.+)$", $"swagger/$1", skipRemainingRules: true);
        }
        // Configure rules for Swagger docs
        // rewrite 'openapi.json' to 'swagger/{Version}/swagger.json'
        rewriterOptions.AddRewrite($"^{DocumentPath}$", $"swagger/{Version}/swagger.json", skipRemainingRules: true);
        app.UseRewriter(rewriterOptions);

        app.UseSwagger();

        if (hostingEnvironment.IsDevelopment())
        {
            app.UseSwaggerUI(options =>
            {
                // NOTE: The leading slash is *very* important in the document path below as the JS served
                //       attempts to workaround a relative path issue that breaks the UI without it
                options.SwaggerEndpoint($"/{DocumentPath}", $"{hostingEnvironment.ApplicationName} {Version}");
            });
        }
    }
        /// <summary>
        /// Setup Request localization, Rewriter and Routing
        /// </summary>
        /// <param name="app">Application builder</param>
        public static void UseRoutingLocalization(this IApplicationBuilder app)
        {
            // Use Request localization
            var locOptions = app.ApplicationServices.GetRequiredService <IOptions <RequestLocalizationOptions> >();

            app.UseRequestLocalization(locOptions.Value);

            var translationRouteRules = app.ApplicationServices.GetServices <ICustomTranslation>().ToList();

            if (translationRouteRules.Any())
            {
                // Use Rewrite rules
                var routeService = app.ApplicationServices.GetRequiredService <IRouteService>();
                routeService.RouteRules.AddRange(translationRouteRules);

                var rewriteOptions = new RewriteOptions();
                foreach (var routeRule in routeService.RouteRules)
                {
                    foreach (var rewriteRule in routeRule.RewriteRules)
                    {
                        rewriteOptions.AddRewrite(rewriteRule.Regex, rewriteRule.Replacement,
                                                  rewriteRule.SkipRemainingRules);
                    }
                }

                app.UseRewriter(rewriteOptions);
            }

            app.UseRouting();
        }
Ejemplo n.º 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)
        {
            var options = new RewriteOptions();

            options.AddRewrite("^/(.*)/(.*)", "$1/$2", false);
            app.UseRewriter(options);



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

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
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.UseHttpsRedirection();

            app.UseStaticFiles();


            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    RequestPath = "/files",
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "file"))
            //});

            //app.UseDirectoryBrowser();
            //app.UseDefaultFiles();
            //app.UseFileServer();



            app.MapWhen(context =>
            {
                return(!context.Request.Path.Value.StartsWith("/api"));
            }, appBuilder =>
            {
                var option = new RewriteOptions();
                option.AddRewrite(".*", "/index.html", true);
                appBuilder.UseRewriter(option);

                appBuilder.UseStaticFiles();
                //appBuilder.Run(async c =>
                //{
                //    var file = env.WebRootFileProvider.GetFileInfo("index.html");

                //    c.Response.ContentType = "text/html";
                //    using (var fileStream = new FileStream(file.PhysicalPath, FileMode.Open, FileAccess.Read))
                //    {
                //        await StreamCopyOperation.CopyToAsync(fileStream, c.Response.Body, null, BufferSize, c.RequestAborted);
                //    }
                //});
            });



            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 5
0
        public static RewriteOptions GetOptions(ApplicationDbContext context)
        {
            var data = new RewriteOptions();

            foreach (var rule in GetAll(context))
            {
                data.AddRewrite(rule.Requested, rule.Target, true);
            }
            return(data);
        }
Ejemplo n.º 6
0
        public static void Apply(IApplicationBuilder app)
        {
            var options = new RewriteOptions();

            new Rewrite("rewrites.json").forEach(
                (origin, destiny) =>
                options.AddRewrite(origin, destiny, true)
                );

            app.UseRewriter(options);
        }
Ejemplo n.º 7
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();
            }
            //sapp.UseDefaultFiles();//设置默认文件,这里包括index.html
            app.UseDirectoryBrowser();
            app.UseStaticFiles();

            #region 指定File文件夹下为静态文件文件夹,和wwwroot共存
            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath  = "/files",
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "File"))
            });
            #endregion

            //非api开头的地址,都从写到index.html(目前主流spa)
            app.MapWhen(context =>
            {
                return(!context.Request.Path.Value.StartsWith("/api"));
            }, appBuilder =>
            {
                var option = new RewriteOptions();
                option.AddRewrite(".*", "/index.html", true);
                appBuilder.UseRewriter(option);

                appBuilder.UseStaticFiles();
                //推荐上面静态文件中间件方式,不是下面这种自己输出文件的方式,下面这种是缓存用到的请求头
                //appBuilder.Run(async c =>
                //{
                //    var file = env.WebRootFileProvider.GetFileInfo("index.html");

                //    c.Response.ContentType = "text/html";
                //    using (var fileStream = new FileStream(file.PhysicalPath, FileMode.Open, FileAccess.Read))
                //    {
                //        await StreamCopyOperation.CopyToAsync(fileStream, c.Response.Body, null, BufferSize, c.RequestAborted);
                //    }
                //});
            });



            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 8
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AspNetCore.StaticFileMiddle.Pratice v1"));
            }

            app.UseHttpsRedirection();
            //启动静态文件路径浏览
            //app.UseDirectoryBrowser();
            //启用访问静态文件中间件
            app.UseStaticFiles();
            //使用自定义目录
            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath  = "/staticfiles",
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFile"))
            });

            app.MapWhen(context =>
            {
                return(!context.Request.Path.Value.StartsWith("/api"));
            },
                        //重定向方式
                        appBuilder =>
            {
                var option = new RewriteOptions();
                option.AddRewrite(".*", "/index.html", true);
                appBuilder.UseStaticFiles();
                //使用断路器的方式
                //appBuilder.Run(async c =>
                //{
                //    var file = env.WebRootFileProvider.GetFileInfo("index.html");
                //    c.Response.ContentType = "text/html";
                //    using (var fileStream = new FileStream(file.PhysicalPath, FileMode.Open, FileAccess.Read))
                //    {
                //        await StreamCopyOperation.CopyToAsync(fileStream, c.Response.Body, null,BufferSize, c.RequestAborted);
                //    }
                //});
            }
                        );
            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
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, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            /*
             * 设定默认文件为index
             * 即:https://localhost:5001/=https://localhost:5001/index.html,https://localhost:5001/a=https://localhost:5001/a/index.html
             * app.UseDefaultFiles();
             */

            /*
             * 开启目录浏览
             * app.UseDirectoryBrowser();
             */

            //默认静态文件根目录为wwwroot
            app.UseStaticFiles();

            app.MapWhen(context =>
            {
                return(!context.Request.Path.Value.StartsWith("/api"));
            }, appBuilder =>
            {
                var option = new RewriteOptions();
                option.AddRewrite(regex: ".*", replacement: "/index.html", skipRemainingRules: true);
                appBuilder.UseRewriter(option);
                appBuilder.UseStaticFiles();
            });

            /*
             * // 谁注册谁优先匹配
             * app.UseStaticFiles(new StaticFileOptions()
             * {
             *  RequestPath = "/myfiles", //指定哪个请求链接
             *  FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "file")) //指定本地路径
             * });
             */

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
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, IWebHostEnvironment env)
        {
            //if (env.IsDevelopment())
            //{
            app.UseDeveloperExceptionPage();
            //}
            //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();
            //}

            var reg = new RewriteOptions();

            reg.AddRedirect("^$", "home/index");
            reg.AddRewrite("^home$", "home/index", true);
            reg.AddRewrite("^api$", "home/api", true);
            app.UseRewriter(reg);

            app.UseCookiePolicy();
            app.UseAuthentication();
            //app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSwagger().UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Clarity API V1");
            });
        }
Ejemplo n.º 11
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
#if !DEBUG
            app.UseStaticFiles();
            app.UseFileServer();
#endif
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var options = new RewriteOptions();
            options.AddRewrite(@"api/(.*).send/(.*)/(.*)", "api/send?token=$1&title=$2&data=$3", true);
            options.AddRewrite(@"api/(.*).send/(.*)", "api/send?token=$1&title=$2", true);

            app.UseRewriter(options);
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 12
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("/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();
            }

            app.UseHttpsRedirection();

            // app.UseDirectoryBrowser();

            // 預設呈現的檔案
            // app.UseDefaultFiles();

            // 可以看到指定目錄底下的檔案
            // app.UseStaticFiles(new StaticFileOptions
            // {
            //     RequestPath  = "/ggg",
            //     FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "files"))
            // });
            // app.UseStaticFiles();

            app.MapWhen(context => !context.Request.Path.Value.StartsWith("api"), builder =>
            {
                var options = new RewriteOptions();
                options.AddRewrite(".*", "/index.html", true);
                builder.UseRewriter(options);
                builder.UseStaticFiles();
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public static void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var rewriteOptions = new RewriteOptions();

            if (env.IsDevelopment())
            {
                rewriteOptions
                .AddRedirect("^$", "docs");
            }
            else
            {
                rewriteOptions
                .AddRewrite(@"^/((?!\.).)*$", "index.html", true);
            }

            app.UseRewriter(rewriteOptions);
        }
Ejemplo n.º 14
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            var rewriteOptions = new RewriteOptions();

            if (env.IsProduction())
            {
                rewriteOptions.AddRedirectToHttps();
            }

            rewriteOptions.AddRewrite(@"^(?:(?!.*\.ico$|assets|bundle).)*$", "index.html", true);

            app
            .UseRewriter(rewriteOptions)
            .UseStaticFiles();
        }
Ejemplo n.º 15
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.UseStaticFiles();

            app.MapWhen(httpContext => !httpContext.Request.Path.Value.StartsWith("/api"), applicationBuilder =>
            {
                var options = new RewriteOptions();
                options.AddRewrite(".*", "/index.html", true);
                applicationBuilder.UseRewriter(options);

                applicationBuilder.UseStaticFiles();
            });
            IFileProvider
            //设置额外的文件路径规则, 默认的文件路径是wwwroot
            //app.UseStaticFiles(new StaticFileOptions{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "file")),
            //    RequestPath = "/files"
            //});

            //设置开启所有文件中间层
            //app.UseFileServer();

            //设置文件夹虚拟路径显示
            //app.UseDirectoryBrowser();

            //设置默认文件匹配规则index.html index.cshtml
            //app.UseDefaultFiles();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider)
        {
            // Error Handling
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            app.UseExceptionHandler("/error");
            app.UseStatusCodePagesWithReExecute("/error/{0}");

            // Authentication
            app.UseAuthentication();

            // Rewrite SPA routes to index
            var options = new RewriteOptions();

            if (!env.IsDevelopment())
            {
                options.AddRedirectToHttps();
            }
            options.AddRewrite("^configure/.*", "/", skipRemainingRules: true)
            .AddRewrite("^customize(/.*)?", "/", skipRemainingRules: true)
            .AddRewrite("^welcome(/.*)?", "/onboarding", skipRemainingRules: true);
            app.UseRewriter(options);

            // Static assets
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Content/build"))
            });
            app.UseStaticFiles(new StaticFileOptions()
            {
                RequestPath  = "/dropin",
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Content/dropin"))
            });

            // MVC route handling
            app.UseMvc();
            app.UseSwagger();
            //app.UseSwaggerUI(o =>
            //{
            //    o.SwaggerEndpoint($"/swagger/v1/swagger.json", "v1");
            //});
        }
        public static void UseRedirects(this IApplicationBuilder app, IConfiguration configuration)
        {
            var redirectSection  = configuration.GetSection(nameof(RedirectSettings));
            var redirectSettings = redirectSection.Get <RedirectSettings>();

            var options = new RewriteOptions();

            if (redirectSettings.Enabled)
            {
                foreach (var redirect in redirectSettings.Redirects)
                {
                    options = options.AddRedirect(redirect.From, redirect.To, (int)redirect.StatusCode);
                }
            }

            // Fingerprint rewrite
            options = options.AddRewrite("([\\S]+)(/v[0-9]+/)([\\S]+)", "$1/$3", false);

            app.UseRewriter(options);
        }
Ejemplo n.º 18
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.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Images")),
                RequestPath  = new PathString("/Images")
            });

            app.UseStaticFiles();

            app.UseMvcWithDefaultRoute();

            app.UseAuthentication();

            //
            var options = new RewriteOptions();

            options.AddRewrite("^rewrite/(.*)", "home/center", true).Add(reContext => {
                reContext.Result = RuleResult.EndResponse;
            });
            //options.AddRedirect("^redirect/(.*)", "api/test");//默认状态码为 302
            //options.AddRedirect("^redirect/(.*)", "home/center", 301);
            app.UseRewriter(options);

            app.Run(async context =>
            {
                //注意重定向和重写URL两种情况下,浏览器地址栏和页面显示的 URL 的区别.
                await context.Response.WriteAsync($"URL:{context.Request.Path + context.Request.QueryString}");
            });

            app.UseMvc();
            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});
        }
Ejemplo n.º 19
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            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();
            }

            app.UseHttpsRedirection();

            app.UseStaticFiles();
            app.MapWhen(context =>
            {
                return(!context.Request.Path.Value.StartsWith("/api"));
            }, builder =>
            {
                var options = new RewriteOptions();
                options.AddRewrite(".*", "/index.html", true);

                builder.UseRewriter(options);
                builder.UseStaticFiles();
            });
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    "default",
                    "{controller=Home}/{action=Index}/{id?}");
            });
        }
Ejemplo n.º 20
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();
            }

            var rewriter = new RewriteOptions();

            rewriter.AddRewrite("^$", "home.html", skipRemainingRules: false);
            app.UseRewriter(rewriter);

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 21
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.UseDefaultFiles();
            app.UseStaticFiles();//默认去wwwroot找静态文件
            //app.UseDirectoryBrowser();

            //去指定的目录寻找静态文件,并且可以把任意目录映射为任意的url
            app.UseStaticFiles(new StaticFileOptions()
            {
                RequestPath  = "/myfiles",
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "file"))
            });

            //非api访问重定向到目录下的index.html,前提是原来的url找不到的情况下,才走这个匹配
            app.MapWhen(context => {
                return(!context.Request.Path.Value.StartsWith("/api"));
            }, appBuilder => {
                var options = new RewriteOptions();
                options.AddRewrite(".*", "/index.html", true);
                appBuilder.UseRewriter(options);
                appBuilder.UseStaticFiles();
            });


            //app.UseRouting();

            //app.UseAuthorization();

            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapControllers();
            //});
        }
Ejemplo n.º 22
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // Response cache middleware
            app.UseResponseCaching();

            app.UseStaticFiles();

            // Use Rendertron middleware
            app.UseRendertron();

            // Redirect all requests to the index.html
            var options = new RewriteOptions();

            options.AddRewrite("(.*)", "/index.html", true);
            app.UseRewriter(options);
            app.UseStaticFiles();
        }
Ejemplo n.º 23
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.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});

            app.UseStaticFiles();
            app.UseSession();

            var routeBuilder = new RouteBuilder(app);

            routeBuilder.MapGet("CreateUser", context =>
            {
                var firstName = context.Request.Query["firstName"];
                var lastName  = context.Request.Query["lastName"];
                var email     = context.Request.Query["email"];
                var password  = context.Request.Query["password"];

                var userService = context.RequestServices.GetService <IUserService>();
                userService.RegisterUser(new UserModel
                {
                    FirstName = firstName,
                    LastName  = lastName,
                    Email     = email,
                    Password  = password
                });

                return(context.Response.WriteAsync($"User {firstName} {lastName} has been successfully created"));
            });

            var newUserRoutes = routeBuilder.Build();

            app.UseRouter(newUserRoutes);

            var options = new RewriteOptions();

            options.AddRewrite("/NewUser", "/UserRegistration/Index", false);
            app.UseRewriter();

            app.UseWebSockets();
            app.UseCommunicationMiddleware();

            var supportedCultures   = CultureInfo.GetCultures(CultureTypes.AllCultures);
            var localizationOptions = new RequestLocalizationOptions
            {
                DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-GB"),
                SupportedCultures     = supportedCultures,
                SupportedUICultures   = supportedCultures
            };

            localizationOptions.RequestCultureProviders.Clear();
            localizationOptions.RequestCultureProviders.Add(new CultureProviderResolverService());

            app.UseRequestLocalization(localizationOptions);

            //app.UseDirectoryBrowser();
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller=Home}/{action=Index}");

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

            app.UseStatusCodePages("text/plain", "HTTP Error - Status Code: {0}");
        }
Ejemplo n.º 24
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() || env.IsStaging())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseDeveloperExceptionPage();
                //app.UseExceptionHandler("/Home/Error");
            }

            var appConfig     = new AppConfiguration(Configuration);
            var currentConfig = new Lazy <string>(() =>
            {
                return(JsonConvert.SerializeObject(appConfig, new JsonSerializerSettings
                {
                    Formatting = Formatting.None,
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                }));
            });

            app.UseRouter(r =>
            {
                r.MapGet("assets/app-config.json", async(ctx) =>
                {
                    ctx.Response.ContentType = "application/json";
                    await ctx.Response.WriteAsync(currentConfig.Value);
                });

                r.MapGet("robots.txt", async(ctx) =>
                {
                    var siteMapUrl = new UriBuilder(appConfig.SiteMap)
                    {
                        Path = "sitemap.xml"
                    }.Uri;
                    ctx.Response.ContentType = "text/plain";
                    var text = string.Join("\n", new []
                    {
                        "User-agent: *",
                        "Allow: /",
                        "",
                        $"Sitemap: {siteMapUrl}",
                        "",
                    });
                    await ctx.Response.WriteAsync(text);
                });

                r.MapGet("sitemap.xml", async(ctx) =>
                {
                    var siteMapUrl = new UriBuilder(appConfig.ApiBaseUrl)
                    {
                        Path = "site-map"
                    }.Uri;
                    using (var siteMapResponse = await httpClient.GetAsync(siteMapUrl, HttpCompletionOption.ResponseHeadersRead))
                        using (var readStream = await siteMapResponse.Content.ReadAsStreamAsync())
                        {
                            ctx.Response.StatusCode = (int)siteMapResponse.StatusCode;
                            siteMapResponse.Headers
                            .Concat(siteMapResponse.Content.Headers)
                            .Where(header => !string.Equals(header.Key, "transfer-encoding", StringComparison.InvariantCultureIgnoreCase))
                            .ToList()
                            .ForEach(header =>
                            {
                                ctx.Response.Headers[header.Key] = header.Value.ToArray();
                            });
                            await readStream.CopyToAsync(ctx.Response.Body);
                        }
                });
            });

            var options = new RewriteOptions();

            if (!(env.IsDevelopment() || env.IsStaging()))
            {
                string domainName = Configuration["Application:CanonicalDomain"];
                if (!String.IsNullOrWhiteSpace(domainName))
                {
                    options.Add(new DomainRewriteRule(domainName));
                }
            }

            options
            .AddRewrite("^$", "index.html", skipRemainingRules: true)
            .AddRewrite("^search($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^auth($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^contact($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^datasets($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^categories($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^login($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^faq($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^issue($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^feedback($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^nominate($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^about($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^privacy-policy($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^usage-terms($|/.*$)", "index.html", skipRemainingRules: true)
            .AddRewrite("^google[a-z0-9]+\\.html$", "assets/$0", skipRemainingRules: true);
            app.UseRewriter(options);
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            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 = "../odr-ui/projects/odr-ui-web";

                if (env.IsDevelopment())
                {
                    // spa.UseAngularCliServer(npmScript: "start");
                    spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
                }
            });
        }
Ejemplo n.º 25
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger <Startup> logger)
        {
            app.UseMiddleware <PerformanceMiddleware>();

            app.UseMiddleware <RequestStoreTestMiddleware>();

            //app.UseResponseCompression();

            app.UseSession();

            app.Use(async(context, next) =>
            {
                if (!context.Session.IsAvailable)
                {
                    logger.LogWarning("Session is NOT awailable");
                    await next();
                    return;
                }

                if (!context.Session.Keys.Contains("_myVal"))
                {
                    context.Session.SetString("_myVal", "fooBar");
                }
                await next();
            });


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

                //app.UseHsts();
            }

            var rewriteOptions = new RewriteOptions();

            ////https://localhost:/homeindex => https://localhost:/index-home
            //rewriteOptions.AddRedirect("^(home)(index)$","$2-$1");
            ////better to use app.UseHttpsRedirection()
            //rewriteOptions.AddRedirectToHttps((int)HttpStatusCode.TemporaryRedirect, 44324);
            ////Template for redirectiong from www domain
            //rewriteOptions.AddRedirectToNonWww();
            ////Template for redirectiong to www domain
            //rewriteOptions.AddRedirectToWww();
            rewriteOptions.AddRewrite("(?i)^privacy$", "Home/Privacy", true);

            app.UseRewriter(rewriteOptions);

            //app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

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

            app.UseEndpoints(endpoints =>
            {
                //Маршрутизация областей: (работают все три варианта)
                endpoints.MapControllerRoute("areas", "{area:myExists}/{controller=Home}/{action=Index}/{id?}");
                //MapAreaControllerRoute лучше использовать для определенных областей и маршрутов, для стандартного маршрута лучше использовать MapControllerRoute
                //endpoints.MapAreaControllerRoute("cabinet", "Cabinet", "{area:myExists}/{controller=Home}/{action=Index}/{id?}");
                //endpoints.MapAreaControllerRoute("cabinet", "Cabinet", "cabinet/{controller=Home}/{action=Index}/{id?}");//полезно, если маршрут не совпадает с названием области

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

                endpoints.MapControllerRoute("test", "testLink{foo}-{bar}", new { controller = "Home", action = "Index" });

                endpoints.MapHub <ChatHub>("/chat", opts => { });
                endpoints.MapHub <NotificationHub>("/notify", opts => { });

                endpoints.MapHealthChecks("/health", new HealthCheckOptions
                {
                    Predicate = check => check.Tags.Contains("tag1")
                });
                endpoints.MapHealthChecks("/healthsql", new HealthCheckOptions
                {
                    Predicate = check => check.Name == "sql_server"
                });
                endpoints.MapHealthChecks("/health2", new HealthCheckOptions
                {
                    AllowCachingResponses = false,
                    //Predicate = check => check.Name == "failed_check",
                    ResultStatusCodes = new Dictionary <HealthStatus, int>
                    {
                        { HealthStatus.Healthy, StatusCodes.Status200OK },
                        { HealthStatus.Degraded, StatusCodes.Status200OK },
                        { HealthStatus.Unhealthy, StatusCodes.Status503ServiceUnavailable }
                    },
                    ResponseWriter = JsonWriter
                });
                endpoints.MapHealthChecks("/health/ready", new HealthCheckOptions
                {
                    Predicate = check => check.Tags.Contains("ready")
                });
                endpoints.MapHealthChecks("/health/live", new HealthCheckOptions
                {
                    Predicate = _ => false
                });
            });
        }
Ejemplo n.º 26
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Use(next => context =>
            {
                context.Request.EnableBuffering();
                return(next(context));
            });

            var options = new RewriteOptions();

            options.Add(rewriteContext =>
            {
                Match match;
                if (rewriteContext.HttpContext.Request.Path == "/")
                {
                    var queryValue = rewriteContext.HttpContext.Request.QueryString.Value;
                    match          = Regex.Match(queryValue, @"^\?act=(.*)/(.*)/(.*)/(.*)$");

                    if (match.Success)
                    {
                        var groups = match.Groups;
                        rewriteContext.HttpContext.Request.Path        = @"/api/send";
                        rewriteContext.HttpContext.Request.QueryString = new QueryString($"?token={groups[2]}&title={groups[3]}&data={groups[4]}");
                    }
                    else
                    {
                        match = Regex.Match(queryValue, @"^\?act=(.*)/(.*)/(.*)$");
                        if (match.Success)
                        {
                            var groups = match.Groups;
                            rewriteContext.HttpContext.Request.Path        = @"/api/send";
                            rewriteContext.HttpContext.Request.QueryString = new QueryString($"?token={groups[2]}&title={groups[3]}");
                        }
                        else
                        {
                            match = Regex.Match(queryValue, @"^\?act=(.*)/(.*)$");
                            if (match.Success)
                            {
                                var groups = match.Groups;
                                rewriteContext.HttpContext.Request.Path        = @"/api/send";
                                rewriteContext.HttpContext.Request.QueryString = new QueryString($"?token={groups[2]}");
                            }
                            else if (rewriteContext.HttpContext.Request.QueryString.Value.StartsWith("?"))
                            {
                                var groups = match.Groups;
                                rewriteContext.HttpContext.Request.Path        = @"/info";
                                rewriteContext.HttpContext.Request.QueryString = new QueryString();
                            }
                        }
                    }
                }
                rewriteContext.Result = RuleResult.ContinueRules;
            });
            options.AddRewrite(@"^api/(.*).send/(.*)/(.*)", "api/send?token=$1&title=$2&data=$3", true);
            options.AddRewrite(@"^api/(.*).send/(.*)", "api/send?token=$1&title=$2", true);

            options.AddRewrite(@"^(.*).send/(.*)/(.*)", "api/send?token=$1&title=$2&data=$3", true);
            options.AddRewrite(@"^(.*).send/(.*)", "api/send?token=$1&title=$2", true);

            app.UseRewriter(options);
            app.UseRouting();

            app.UseStaticFiles();
            app.UseFileServer();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 27
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.UseDirectoryBrowser();//中间件调用顺序 去掉访问默认页设置,否则会直接到默认页上

            //2 设置默认访问页: index/default
            //app.UseDefaultFiles();


            //1 定义两个静态文件目录时,会先找wwwroot找不到再找file,但是定义了StaticFileOptions 的path之后,只找file的映射目录

            app.UseStaticFiles();

            //1.1 映射出file目录
            app.UseStaticFiles(new StaticFileOptions
            {
                // RequestPath = "/files",// RequestPath 是url地址, 缺省该参数,默认映射到站点根地址,请求 https://localhost:5001,将请求映射到file文件夹
                //定义了RequestPath之后 请求 https://localhost:5001/files, 将映射到file文件夹
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "file")) // 文件系统中的文件结构,物理文件路径 file/page.html
            });

            //app.UseFileServer();

            app.MapWhen(context =>
            {
                return(!context.Request.Path.Value.StartsWith("/api"));// 不是API的请求都重定向到 index.html
            }, appBuilder =>
            {
                var option = new RewriteOptions();
                option.AddRewrite(".*", "/index.html", true);
                appBuilder.UseRewriter(option);

                appBuilder.UseStaticFiles(); // 然后再使用静态文件

                //直接输出文件的方式中的HttpRequest 的header是不一样的
                //appBuilder.Run(async c =>
                //{
                //    var file = env.WebRootFileProvider.GetFileInfo("index.html");

                //    c.Response.ContentType = "text/html";
                //    using (var fileStream = new FileStream(file.PhysicalPath, FileMode.Open, FileAccess.Read))
                //    {
                //        await StreamCopyOperation.CopyToAsync(fileStream, c.Response.Body, null, BufferSize, c.RequestAborted);
                //    }
                //});
            });



            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
        // 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();
            }

            #region Exception

            //app.UseExceptionHandler(errApp =>
            //{
            //    errApp.Run(async context =>
            //    {
            //        var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
            //        IKnownException knownException = exceptionHandlerPathFeature.Error as IKnownException;
            //        if (knownException == null)
            //        {
            //            //var logger = context.RequestServices.GetService<ILogger<MyExceptionFilterAttribute>>();
            //            //logger.LogError(exceptionHandlerPathFeature.Error, exceptionHandlerPathFeature.Error.Message);
            //            knownException = KnownException.Unknown;
            //            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            //        }
            //        else
            //        {
            //            knownException = KnownException.FromKnownException(knownException);
            //            context.Response.StatusCode = StatusCodes.Status200OK;
            //        }
            //        var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();
            //        context.Response.ContentType = "application/json; charset=utf-8";
            //        await context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(knownException, jsonOptions.Value.JsonSerializerOptions));
            //    });
            //});

            #endregion

            #region StaticFile
            app.UseDirectoryBrowser(); //在UseDefaultFiles之前
            app.UseDefaultFiles();     //在UseStaticFiles之前
            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath  = "/files",                                                                       //http://localhost:5000/files/page.html
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "file")) //http://localhost:5000/page.html
            });
            app.UseStaticFiles();

            app.MapWhen(context =>
            {
                return(!context.Request.Path.Value.StartsWith("/api"));
            }, appBuilder =>
            {
                var option = new RewriteOptions();
                option.AddRewrite(".*", "/index.html", true);
                appBuilder.UseRewriter(option);

                appBuilder.UseStaticFiles();
                //appBuilder.Run(async c =>
                //{
                //    var file = env.WebRootFileProvider.GetFileInfo("index.html");

                //    c.Response.ContentType = "text/html";
                //    using (var fileStream = new FileStream(file.PhysicalPath, FileMode.Open, FileAccess.Read))
                //    {
                //        await StreamCopyOperation.CopyToAsync(fileStream, c.Response.Body, null, BufferSize, c.RequestAborted);
                //    }
                //});
            });
            #endregion

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 29
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";
                });
            }
        }