// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var options = new RewriteOptions() .AddRewrite("^_framework/_bin/(.*)\\.blazor", "_framework/_bin/$1.dll", skipRemainingRules: true); app.UseRewriter(options); app.UseResponseCompression(); /*app.Use(async (context, next) => * { * * if (!context.Request.Path.HasValue || * (context.Request.Path.Value != "/_framework/blazor.boot.json" && context.Request.Path.Value != "/_framework/blazor.webassembly.js")) * { * await next(); * return; * } * var newContent = string.Empty; * * var existingBody = context.Response.Body; * * using (var newBody = new MemoryStream()) * { * // We set the response body to our stream so we can read after the chain of middlewares have been called. * context.Response.Body = newBody; * * await next(); * * // Reset the body so nothing from the latter middlewares goes to the output. * context.Response.Body = new MemoryStream(); * * newBody.Seek(0, SeekOrigin.Begin); * context.Response.Body = existingBody; * // newContent will be `Hello`. * newContent = new StreamReader(newBody).ReadToEnd(); * * newContent = newContent.Replace(".dll",".toto"); * * // Send our modified content to the response body. * await context.Response.WriteAsync(newContent); * } * });*/ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("fr"), }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en"), // Formatting numbers, dates, etc. SupportedCultures = supportedCultures, // UI strings that we have localized. SupportedUICultures = supportedCultures }); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "/api/{controller}/{action}/{id?}"); }); app.UseMiddleware <CsrfTokenCookieMiddleware>(); app.UseBlazor <Toss.Client.Program>(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // app.UseStatusCodePages(); // app.UseStatusCodePages(async context => { // context.HttpContext.Response.ContentType = "text/plain"; // await context.HttpContext.Response.WriteAsync($"What your statuscode get is :{context.HttpContext.Response.StatusCode}"); // }); app.UseStatusCodePagesWithReExecute("/error", "?StatusCode={0}"); app.UseOnlyPassGet(); // app.UseErrorHandler(); //app.UseStatusCodePagesWithRedirects("/error"); app.UseStaticFiles(); // env.EnvironmentName = EnvironmentName.Development; // if (env.IsDevelopment()) // { // app.UseDeveloperExceptionPage(); // } // else // { // app.UseExceptionHandler("/error");//It is something like rewrite url ? // } #region Add route /files for invoke specific StaticFile //app.UseStaticFiles(new StaticFileOptions() //{ // FileProvider = new PhysicalFileProvider( // Path.Combine(Directory.GetCurrentDirectory(), @"StaticFile")), // RequestPath = new PathString("/files"), // OnPrepareResponse = orp => // { // orp.Context.Response.Headers.Append("Cache-Control", "Public,max-age=600"); // } //}); #endregion //Custom Middleware RequestCulture app.UseRequestCulture(); // route localhost:5000/map1 app.Map("/map1", HandleMap1); //route localhost:5000/map2 app.Map("/map2", HandleMap2); //route localhost:5000/?para={_} app.MapWhen(context => context.Request.Query.ContainsKey("para"), HandleMapWhenBranch); #region Url Rewrite and Redirect using (StreamReader apacheModRewriteStreamReader = File.OpenText("ApacheModRewrite.txt")) using (StreamReader iisUrlRewriteStreamReader = File.OpenText("IISUrlRewrite.xml")) { var options = new RewriteOptions() .AddRedirect("redirect-rule/(.*)", "redirected/$1") .AddRewrite(@"^rewrite-rule/(\d+)/(\d+)", "rewritten?var1=$1&var2=$2", skipRemainingRules: true) .AddApacheModRewrite(apacheModRewriteStreamReader) .AddIISUrlRewrite(iisUrlRewriteStreamReader); app.UseRewriter(options); } #endregion app.UseMvc(routes => { routes.MapRoute( name: "Regex", template: "MultiRegex/{param1}/{param2}", defaults: new { controller = "Rewrite", action = "MultiRegexFunc" }, constraints: new { param1 = @"^\d+", param2 = @"\d+" } ); routes.MapRoute( name: "Error", template: "error/", defaults: new { controller = "Home", action = "error" } ); routes.MapRoute( name: "404", template: "404/", defaults: new { controller = "Home", action = "pageNotFound" } ); routes.MapRoute( name: "default", template: "{Controller}/{Action}/{Id?}", 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.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"; }); } }
/// <summary> /// This method gets called by the runtime, and is used to configure the HTTP request pipeline. /// </summary> /// <param name="app">Provides the mechanisms to configure the application's request pipeline.</param> /// <param name="env">An <see cref="IHostingEnvironment"/> used to set up configuration sources.</param> /// <param name="loggerFactory">Used to configure the logging system.</param> /// <param name="localization">Specifies options for the <see cref="RequestLocalizationMiddleware"/>.</param> /// <param name="urls">Provides the URLs for the different hosts which form the application.</param> public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions <RequestLocalizationOptions> localization, IOptions <URLOptions> urls) { loggerFactory.AddNLog(); app.AddNLogWeb(); LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection"); LogManager.Configuration.Variables["logDir"] = Configuration["LogDir"]; if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } var jsnlogConfiguration = new JsnlogConfiguration() { maxMessages = 5, serverSideMessageFormat = "Message: %message | url: %url", ajaxAppenders = new List <AjaxAppender> { new AjaxAppender { name = "ajaxAppender", storeInBufferLevel = "TRACE", level = "INFO", sendWithBufferLevel = "FATAL", bufferSize = 20 } }, loggers = new List <JSNLog.Logger> { new JSNLog.Logger { appenders = "ajaxAppender" } } }; if (env.IsDevelopment()) { jsnlogConfiguration.consoleAppenders = new List <ConsoleAppender> { new ConsoleAppender { name = "consoleAppender" } }; jsnlogConfiguration.loggers[0].appenders = "ajaxAppender;consoleAppender"; } app.UseJSNLog(new LoggingAdapter(loggerFactory), jsnlogConfiguration); var options = new RewriteOptions().AddRedirectToHttps(); app.UseRewriter(options); app.UseCors("default"); app.UseRequestLocalization(localization.Value); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", 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, 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" }); }); }
public static RewriteOptions AddRedirectToHttpsHost(this RewriteOptions options, HostString host) { options.Rules.Add(new RedirectToHttpsHost(host)); return(options); }
// 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()) { // Redirect to HTTPS var options = new RewriteOptions() .AddRedirectToHttps(); app.UseRewriter(options); } if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UsePreventHotLinking(options => { options.HotLinkImagePath = "images/HotLink.jpeg"; options.ExceptedHosts = new List <Uri> { new Uri("https://blogs.u2u.be") }; }); app.UseResponseHeaders(builder => { // builder.SetHeader("Header", "Value"); //builder.SetStrictTransportSecurity(new StrictTransportSecurity //{ // MaxAge = TimeSpan.FromDays(1), // IncludeSubdomains = true, // Preload = false //}); //builder.SetPublicKeyPinning(new PublicKeyPinning //{ // MaxAge = TimeSpan.FromDays(10), // IncludeSubdomains = true, // Pins = new List<string> { // "yh0kYiYm4YN+0DAKp4bB16pGqrQq9btXHMeR9jz834o=", // current certificate // "YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=", // Let's Encrypt Authority X3 // "SEnt86CqqSYlSIlLcfnKdJdoS8NJG1EG+/5b5qtvmUY=" // backup cert // } //}); builder.SetContentSecurityPolicy(new ContentSecurityPolicy() { SupportNonces = true, FrameAncestors = new List <string> { ContentSecurityPolicy.Source.None }, DefaultSrc = new List <string> { ContentSecurityPolicy.Source.Self, "https://www.u2u.be" }, ScriptSrc = new List <string> { ContentSecurityPolicy.Source.Self, // ContentSecurityPolicy.Source.UnsafeInline, "https://ajax.aspnetcdn.com", "'sha256-d5/o7Lq1BQizlE+7YpLcN8kzeapQhf2bAgOX+645XGI='" }, StyleSrc = new List <string> { ContentSecurityPolicy.Source.Self, "https://ajax.aspnetcdn.com", "'sha256-pTnn8NGuYdfLn7/v3BQ2pYxjz73VjHU2Wkr6HjgUgVU='" } }); }); app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Vulnerable}/{action=OWASP}/{id?}"); }); }
// 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) { var logger = loggerFactory.CreateLogger <Startup>(); bool redirectToHttps = bool.Parse(Configuration["Common:RedirectToHttps"] ?? "false"); if (redirectToHttps) { _logger.LogInformation("Enabling RedirectToHttps"); var rewriteOptions = new RewriteOptions() .AddRedirectToHttps(); app.UseRewriter(rewriteOptions); } var serviceSwitchSettings = app.ApplicationServices.GetRequiredService <NetherServiceSwitchSettings>(); app.Initialize <IUserStore>(); app.Initialize <IPlayerManagementStore>(); app.Initialize <ILeaderboardStore>(); app.Initialize <IAnalyticsStore>(); app.Initialize <IApplicationPerformanceMonitor>(); // Set up separate web pipelines for identity, MVC UI, and API // as they each have different auth requirements! if (serviceSwitchSettings.IsServiceEnabled("Identity")) { app.Map("/identity", idapp => { JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); idapp.UseIdentityServer(); idapp.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme, AutomaticAuthenticate = false, AutomaticChallenge = false }); var facebookEnabled = bool.Parse(Configuration["Identity:SignInMethods:Facebook:EnableImplicit"] ?? "false"); if (facebookEnabled) { var appId = Configuration["Identity:SignInMethods:Facebook:AppId"]; var appSecret = Configuration["Identity:SignInMethods:Facebook:AppSecret"]; idapp.UseFacebookAuthentication(new FacebookOptions() { DisplayName = "Facebook", SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme, CallbackPath = "/signin-facebook", AppId = appId, AppSecret = appSecret }); } idapp.UseStaticFiles(); idapp.UseMvc(routes => { routes.MapRoute( name: "account", template: "account/{action}", defaults: new { controller = "Account" }); }); }); } app.Map("/api", apiapp => { apiapp.UseCors(options => { logger.LogInformation("CORS options:"); var config = Configuration.GetSection("Common:Cors"); var allowedOrigins = config.ParseStringArray("AllowedOrigins").ToArray(); logger.LogInformation("AllowedOrigins: {0}", string.Join(",", allowedOrigins)); options.WithOrigins(allowedOrigins); // TODO - allow configuration of headers/methods options .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); var idsvrConfig = Configuration.GetSection("Identity:IdentityServer"); string authority = idsvrConfig["Authority"]; bool requireHttps = idsvrConfig.GetValue("RequireHttps", true); apiapp.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions { Authority = authority, RequireHttpsMetadata = requireHttps, ApiName = "nether-all", AllowedScopes = { "nether-all" }, }); // TODO filter which routes this matches (i.e. only API routes) apiapp.UseMvc(); apiapp.UseSwagger(options => { options.RouteTemplate = "swagger/{documentName}/swagger.json"; }); apiapp.UseSwaggerUI(options => { options.RoutePrefix = "swagger/ui"; options.SwaggerEndpoint("/api/swagger/v0.1/swagger.json", "v0.1 Docs"); options.ConfigureOAuth2("swaggerui", "swaggeruisecret".Sha256(), "swagger-ui-realm", "Swagger UI"); }); }); app.Map("/ui", uiapp => { uiapp.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookies" }); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); var authority = Configuration["Identity:IdentityServer:Authority"]; var uiBaseUrl = Configuration["Identity:IdentityServer:UiBaseUrl"]; // hybrid uiapp.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { AuthenticationScheme = "oidc", SignInScheme = "Cookies", Authority = authority, RequireHttpsMetadata = false, PostLogoutRedirectUri = uiBaseUrl, ClientId = "mvc2", ClientSecret = "secret", ResponseType = "code id_token", Scope = { "api1", "offline_access" }, GetClaimsFromUserInfoEndpoint = true, SaveTokens = true }); uiapp.UseMvc(); // TODO filter which routes this matches (i.e. only non-API routes) }); // serve Landing page static files at root app.UseStaticFiles(new StaticFileOptions { RequestPath = "", FileProvider = new PhysicalFileProvider(Path.Combine(_hostingEnvironment.WebRootPath, "Features", "LandingPage")) }); app.UseMvc(routes => { routes.MapRoute( name: "landing-page", template: "", defaults: new { controller = "LandingPage", action = "Index" } ); }); }
public static IApplicationBuilder UseBindKraft(this IApplicationBuilder app, IHostingEnvironment env) { //AntiforgeryService //app.Use(next => context => //{ // if (string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase)) // { // AntiforgeryTokenSet tokens = app.ApplicationServices.GetService<IAntiforgery>().GetAndStoreTokens(context); // context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false }); // } // return next(context); //}); _KraftGlobalConfigurationSettings.EnvironmentSettings = new KraftEnvironmentSettings(env.ApplicationName, env.ContentRootPath, env.EnvironmentName, env.WebRootPath); try { ILoggerFactory loggerFactory = app.ApplicationServices.GetService <ILoggerFactory>(); DiagnosticListener diagnosticListener = app.ApplicationServices.GetService <DiagnosticListener>(); //First statement to register Error handling !!!Keep at the top!!! app.UseMiddleware <KraftExceptionHandlerMiddleware>(loggerFactory, new ExceptionHandlerOptions(), diagnosticListener); if (_KraftGlobalConfigurationSettings.GeneralSettings.RedirectToWww) { RewriteOptions rewrite = new RewriteOptions(); rewrite.AddRedirectToWwwPermanent(); app.UseRewriter(rewrite); } if (_KraftGlobalConfigurationSettings.GeneralSettings.RedirectToHttps) { app.UseForwardedHeaders(); app.UseHsts(); app.UseHttpsRedirection(); } ExtensionMethods.Init(app, _Logger, _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder); app.UseBindKraftLogger(env, loggerFactory, ERRORURLSEGMENT); app.UseBindKraftProfiler(env, loggerFactory, _MemoryCache); string kraftUrlSegment = _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlSegment; KraftStaticFiles.RegisterStaticFiles(app, _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModuleImages); KraftStaticFiles.RegisterStaticFiles(app, _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModulePublic); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } _Builder = app; BundleCollection bundleCollection = app.UseBundling(env, loggerFactory.CreateLogger("Bundling"), _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlCssJsSegment, _KraftGlobalConfigurationSettings.GeneralSettings.EnableOptimization); bundleCollection.EnableInstrumentations = env.IsDevelopment(); //Logging enabled #region Initial module registration KraftModuleCollection modulesCollection = app.ApplicationServices.GetService <KraftModuleCollection>(); if (!Directory.Exists(_KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder)) { throw new Exception($"No \"{_KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder}\" directory found! The CoreKraft initialization cannot continue."); } try { IApplicationLifetime applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>(); lock (_SyncRoot) { AppDomain.CurrentDomain.UnhandledException += AppDomain_OnUnhandledException; AppDomain.CurrentDomain.AssemblyResolve += AppDomain_OnAssemblyResolve; string[] moduleDirectories = Directory.GetDirectories(_KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder); foreach (string subdirectory in moduleDirectories) { string moduleDirectoryName = new DirectoryInfo(subdirectory).Name; if (moduleDirectoryName != null && moduleDirectoryName.Equals("_PluginsReferences", StringComparison.InvariantCultureIgnoreCase)) { continue; } ICachingService cachingService = app.ApplicationServices.GetService <ICachingService>(); KraftModule kraftModule = modulesCollection.RegisterModule(moduleDirectoryName, cachingService); if (kraftModule == null) { throw new Exception($"Module failed to create for directory \"{moduleDirectoryName}\"."); } //The application will restart when some files changed in the modules directory and subdirectories but only in RELEASE //Check if module is initialized Robert if (kraftModule.IsInitialized && !env.IsDevelopment()) { string moduleFullPath = Path.Combine(_KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder, kraftModule.DirectoryName); AttachModulesWatcher(moduleFullPath, false, applicationLifetime); string path2Data = Path.Combine(moduleFullPath, "Data"); if (!HasWritePermissionOnDir(new DirectoryInfo(path2Data), true)) { throw new SecurityException($"Write access to folder {path2Data} is required!"); } path2Data = Path.Combine(moduleFullPath, "Images"); if (!HasWritePermissionOnDir(new DirectoryInfo(path2Data), true)) { throw new SecurityException($"Write access to folder {path2Data} is required!"); } AttachModulesWatcher(Path.Combine(moduleFullPath, "Css"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "Documentation"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "Localization"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "NodeSets"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "Scripts"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "Templates"), true, applicationLifetime); AttachModulesWatcher(Path.Combine(moduleFullPath, "Views"), true, applicationLifetime); } } //try to construct all modules modulesCollection.ResolveModuleDependencies(); } if (!env.IsDevelopment()) { _Configuration.GetReloadToken().RegisterChangeCallback(_ => { RestartReason restartReason = new RestartReason(); restartReason.Reason = "Configuration Changed"; restartReason.Description = $"'appsettings.Production.json' has been altered"; AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException; AppDomain.CurrentDomain.AssemblyResolve -= AppDomain_OnAssemblyResolve; RestartApplication(applicationLifetime, restartReason); }, null); } } catch (Exception boom) { throw new Exception($"CoreKrafts module construction failed! {boom.Message}"); } #endregion Initial module registration //Configure the CoreKraft routing RouteHandler kraftRoutesHandler = new RouteHandler(KraftMiddleware.ExecutionDelegate(app, _KraftGlobalConfigurationSettings)); app.UseRouter(KraftRouteBuilder.MakeRouter(app, kraftRoutesHandler, kraftUrlSegment)); app.UseSession(); if (_KraftGlobalConfigurationSettings.GeneralSettings.AuthorizationSection.RequireAuthorization) { app.UseAuthentication(); } //KraftKeepAlive.RegisterKeepAliveAsync(builder); //Configure eventually SignalR try { if (_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.UseSignalR) { app.UseSignalR(routes => { MethodInfo mapHub = typeof(HubRouteBuilder).GetMethod("MapHub", new[] { typeof(PathString) }); MethodInfo generic = mapHub.MakeGenericMethod(Type.GetType(_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.HubImplementationAsString)); generic.Invoke(routes, new object[] { new PathString(_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.HubRoute) }); }); } } catch (Exception e) { KraftLogger.LogError("Register signalR middleware. Exception: " + e); } //Signals SignalStartup signalStartup = new SignalStartup(app.ApplicationServices, _KraftGlobalConfigurationSettings); signalStartup.ExecuteSignalsOnStartup(); //End Signals } catch (Exception ex) { KraftLogger.LogError("Method: UseBindKraft ", ex); KraftExceptionHandlerMiddleware.Exceptions[KraftExceptionHandlerMiddleware.EXCEPTIONSONCONFIGURE].Add(ex); } //This is the last statement KraftExceptionHandlerMiddleware.HandleErrorAction(app); return(app); }
/// <summary> /// Redirects from HTTP to HTTPS. /// </summary> /// <param name="applicationBuilder">The application builder.</param> private static void RedirectFromHttpToHttps(IApplicationBuilder applicationBuilder) { var options = new RewriteOptions().AddRedirectToHttps(); applicationBuilder.UseRewriter(options); }
public static IApplicationBuilder UseBindKraft(this IApplicationBuilder app, IWebHostEnvironment env, Action <bool> restart = null) { //AntiforgeryService //app.Use(next => context => //{ // if (string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase)) // { // AntiforgeryTokenSet tokens = app.ApplicationServices.GetService<IAntiforgery>().GetAndStoreTokens(context); // context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false }); // } // return next(context); //}); _KraftGlobalConfigurationSettings.EnvironmentSettings = new KraftEnvironmentSettings(env.ApplicationName, env.ContentRootPath, env.EnvironmentName, env.WebRootPath); try { ILoggerFactory loggerFactory = app.ApplicationServices.GetService <ILoggerFactory>(); DiagnosticListener diagnosticListener = app.ApplicationServices.GetService <DiagnosticListener>(); //First statement to register Error handling !!!Keep at the top!!! app.UseMiddleware <KraftExceptionHandlerMiddleware>(loggerFactory, new ExceptionHandlerOptions(), diagnosticListener); AppDomain.CurrentDomain.UnhandledException += AppDomain_OnUnhandledException; AppDomain.CurrentDomain.AssemblyResolve += AppDomain_OnAssemblyResolve; if (_KraftGlobalConfigurationSettings.GeneralSettings.RedirectToHttps) { app.UseForwardedHeaders(); app.UseHsts(); app.UseHttpsRedirection(); } if (_KraftGlobalConfigurationSettings.GeneralSettings.RedirectToWww) { RewriteOptions rewrite = new RewriteOptions(); rewrite.AddRedirectToWwwPermanent(); app.UseRewriter(rewrite); } app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "wwwroot")), ServeUnknownFileTypes = true, RequestPath = new PathString(string.Empty), }); ExtensionMethods.Init(app, _Logger); ToolSettings tool = KraftToolsRouteBuilder.GetTool(_KraftGlobalConfigurationSettings, "errors"); string segment = null; if (tool != null && tool.Enabled)//Errors enabled from configuration { segment = tool.Url; } app.UseBindKraftLogger(env, loggerFactory, segment); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } string rootVirtualPath = "/modules"; BundleCollection bundleCollection = app.UseBundling(env, _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders, rootVirtualPath, loggerFactory.CreateLogger("Bundling"), _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlCssJsSegment, _KraftGlobalConfigurationSettings.GeneralSettings.EnableOptimization); bundleCollection.EnableInstrumentations = env.IsDevelopment(); //Logging enabled #region Initial module registration foreach (string dir in _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders) { if (!Directory.Exists(dir)) { throw new Exception($"No \"{dir}\" directory found in the setting ModulesRootFolders! The CoreKraft initialization cannot continue."); } } string kraftUrlSegment = _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlSegment; try { KraftModuleCollection modulesCollection = app.ApplicationServices.GetService <KraftModuleCollection>(); IHostApplicationLifetime applicationLifetime = app.ApplicationServices.GetRequiredService <IHostApplicationLifetime>(); lock (_SyncRoot) { KraftModulesConstruction kraftModulesConstruction = new KraftModulesConstruction(); Dictionary <string, IDependable <KraftDependableModule> > kraftDependableModules = kraftModulesConstruction.Init(_KraftGlobalConfigurationSettings.GeneralSettings.DefaultStartModule, _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders); ICachingService cachingService = app.ApplicationServices.GetService <ICachingService>(); Dictionary <string, string> moduleKey2Path = new Dictionary <string, string>(); foreach (KeyValuePair <string, IDependable <KraftDependableModule> > depModule in kraftDependableModules) { KraftDependableModule kraftDependable = (depModule.Value as KraftDependableModule); KraftModule kraftModule = modulesCollection.RegisterModule(kraftDependable.KraftModuleRootPath, depModule.Value.Key, kraftDependable, cachingService); KraftStaticFiles.RegisterStaticFiles(app, kraftModule.ModulePath, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModuleImages); KraftStaticFiles.RegisterStaticFiles(app, kraftModule.ModulePath, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModulePublic); moduleKey2Path.Add(kraftModule.Key, kraftDependable.KraftModuleRootPath); string moduleFullPath = Path.Combine(kraftDependable.KraftModuleRootPath, kraftModule.Key); string path2Data = Path.Combine(moduleFullPath, "Data"); if (!HasWritePermissionOnDir(new DirectoryInfo(path2Data), true)) { throw new SecurityException($"Write access to folder {path2Data} is required!"); } path2Data = Path.Combine(moduleFullPath, "Images"); if (!HasWritePermissionOnDir(new DirectoryInfo(path2Data), true)) { throw new SecurityException($"Write access to folder {path2Data} is required!"); } foreach (string validSubFolder in _ValidSubFoldersForWatching) { AttachModulesWatcher(Path.Combine(moduleFullPath, validSubFolder), true, applicationLifetime, restart); } } _KraftGlobalConfigurationSettings.GeneralSettings.ModuleKey2Path = moduleKey2Path; } #region Watching appsettings, PassThroughJsConfig, nlogConfig //appsettings.{Production} configuration watch _Configuration.GetReloadToken().RegisterChangeCallback(_ => { string environment = "Production"; if (env.IsDevelopment()) { environment = "Development"; } RestartReason restartReason = new RestartReason { Reason = "appsettings-Configuration Changed", Description = $"'appsettings.{environment}.json' has been altered" }; AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException; AppDomain.CurrentDomain.AssemblyResolve -= AppDomain_OnAssemblyResolve; RestartApplication(applicationLifetime, restartReason, restart); }, null); //PassThroughJsConfig configuration watch IChangeToken changeTokenPassThroughJsConfig = _KraftGlobalConfigurationSettings.GeneralSettings.BindKraftConfigurationGetReloadToken(env); if (changeTokenPassThroughJsConfig != null) { changeTokenPassThroughJsConfig.RegisterChangeCallback(_ => { RestartReason restartReason = new RestartReason { Reason = "PassThroughJsConfig Changed", Description = $"'{_KraftGlobalConfigurationSettings.GeneralSettings.PassThroughJsConfig}' has been altered" }; AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException; AppDomain.CurrentDomain.AssemblyResolve -= AppDomain_OnAssemblyResolve; RestartApplication(applicationLifetime, restartReason, restart); }, null); } FileInfo nlogConfig = new FileInfo(Path.Combine(env.ContentRootPath, "nlog.config")); if (nlogConfig.Exists) { IChangeToken changeTokenNlogConfig = env.ContentRootFileProvider.Watch(nlogConfig.Name); if (changeTokenNlogConfig != null) { changeTokenNlogConfig.RegisterChangeCallback(_ => { RestartReason restartReason = new RestartReason { Reason = "Nlog.config Changed", Description = $"'Nlog.config' has been altered" }; AppDomain.CurrentDomain.UnhandledException -= AppDomain_OnUnhandledException; AppDomain.CurrentDomain.AssemblyResolve -= AppDomain_OnAssemblyResolve; RestartApplication(applicationLifetime, restartReason, restart); }, null); } } #endregion End: Watching appsettings, PassThroughJsConfig, nlogConfig } catch (Exception boom) { KraftLogger.LogError(boom); throw new Exception($"CoreKrafts module construction failed! {boom.Message}"); } #endregion Initial module registration //Configure the CoreKraft routing RouteHandler kraftRoutesHandler = new RouteHandler(KraftMiddleware.ExecutionDelegate(app, _KraftGlobalConfigurationSettings)); app.UseRouter(KraftRouteBuilder.MakeRouter(app, kraftRoutesHandler, kraftUrlSegment)); #region Tools routing KraftToolsRouteBuilder.MakeRouters(app, _KraftGlobalConfigurationSettings); #endregion Tools routing DirectCallService.Instance.Call = KraftMiddleware.ExecutionDelegateDirect(app, _KraftGlobalConfigurationSettings); app.UseSession(); if (_KraftGlobalConfigurationSettings.GeneralSettings.AuthorizationSection.RequireAuthorization) { app.UseAuthentication(); } //KraftKeepAlive.RegisterKeepAliveAsync(builder); //Configure eventually SignalR try { if (_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.UseSignalR) { app.UseRouting(); app.UseEndpoints(endpoints => { MethodInfo mapHub = typeof(HubEndpointRouteBuilderExtensions).GetMethod( "MapHub", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IEndpointRouteBuilder), typeof(string), typeof(Action <HttpConnectionDispatcherOptions>) }, null); MethodInfo generic = mapHub.MakeGenericMethod(Type.GetType(_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.HubImplementationAsString, true)); generic.Invoke(null, new object[] { endpoints, new string(_KraftGlobalConfigurationSettings.GeneralSettings.SignalRSettings.HubRoute), (Action <HttpConnectionDispatcherOptions>)(x => { x.ApplicationMaxBufferSize = 3200000; x.WebSockets.CloseTimeout = TimeSpan.FromSeconds(30); x.LongPolling.PollTimeout = TimeSpan.FromSeconds(180); }) }); }); } } catch (Exception e) { KraftLogger.LogError("Register signalR middleware. Exception: " + e); } //Signals SignalStartup signalStartup = new SignalStartup(app.ApplicationServices, _KraftGlobalConfigurationSettings); signalStartup.ExecuteSignalsOnStartup(); //End Signals } catch (Exception ex) { KraftLogger.LogError("Method: UseBindKraft ", ex); KraftExceptionHandlerMiddleware.Exceptions[KraftExceptionHandlerMiddleware.EXCEPTIONSONCONFIGURE].Add(ex); } //This is the last statement KraftExceptionHandlerMiddleware.HandleErrorAction(app); return(app); }
// 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?}"); }); }
// 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(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); //Set password with the Secret Manager tool //dotnet user-secrets set SeedUserPW <PW> var AdminUserPW = Configuration["SeedUserPW"]; if (string.IsNullOrEmpty(AdminUserPW)) { /* * throw new SystemException("Use Secret Manager Tool to set SeedUserPW. \n" + * "dotnet user-secrets set SeedUserPW <PW>"); */ AdminUserPW = "123..abc"; } //var empty = SeedMembers.EnsureRole(app.ApplicationServices, "bf2a756-3dd4-4883-b2b4-33fdcec9b9d2", Constants.EnrollmentAdministratorsRole); /* * try * {*/ //SeedMembers.Initialize(app.ApplicationServices, "").Wait(); /* * } * catch * { * throw new SystemException("You need to update the Database " + "\nPM Update-Database " + "\n or \n" + + ">dotnet ef database update" + "\nIf that doesn't work, comment out SeedMembers and register a new User."); + } */ // Redirect HTTP to HTTPS var options = new RewriteOptions() .AddRedirectToHttps(); app.UseRewriter(options); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseDefaultFiles(); var contentTypeProvider = new FileExtensionContentTypeProvider(); contentTypeProvider.Mappings[".nzd"] = "application/octet-stream"; // TODO: Remove nzd serving, and serve via GCS instead. // TODO: Add each API directory separately. app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = contentTypeProvider }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "docfx")) }); // Captures "unstable" or a specific version - used several times below. string anyVersion = @"((?:1\.[0-3]\.x)|(?:unstable))"; var rewriteOptions = new RewriteOptions() // Docfx wants index.html to exist, which is annoying... just redirect. .AddRedirect($@"^index.html$", "/") // We don't have an index.html or equivalent for the APIs, so let's go to NodaTime.html .AddRedirect($@"^{anyVersion}/api/?$", "$1/api/NodaTime.html") // Compatibility with old links .AddRedirect($@"^{anyVersion}/userguide/([^.]+)\.html$", "$1/userguide/$2") // Avoid links from userguide/unstable from going to userguide/core-concepts etc // (There are no doubt better ways of doing this...) .AddRedirect($@"^{anyVersion}/userguide$", "$1/userguide/") .AddRedirect($@"^developer$", "developer/") // Make /api and /userguide links to the latest stable release. .AddRedirect("^(api|userguide)((?:/.*))$", "1.3.x/$1$2"); app.UseRewriter(rewriteOptions); // At some stage we may want an MVC view for the home page, but at the moment // we're just serving static files, so we don't need much. app.UseMvc(routes => { // TODO: Find a better way of routing. This is pretty nasty. routes.MapRoute("Developer docs", "developer/{*url}", new { controller = "Documentation", bundle = "developer", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("1.0.x user guide", "1.0.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.0.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("1.1.x user guide", "1.1.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.1.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("1.2.x user guide", "1.2.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.2.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("1.3.x user guide", "1.3.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.3.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("Unstable user guide", "unstable/userguide/{*url}", new { controller = "Documentation", bundle = "unstable", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IDasBlogSettings dasBlogSettings) { (var siteOk, var siteError) = RepairSite(app); if (env.IsDevelopment() || env.IsStaging()) { app.UseDeveloperExceptionPage(); //app.UseBrowserLink(); } else { app.UseExceptionHandler("/home/error"); } if (env.IsStaging() || env.IsProduction()) { app.UseHsts(options => options.MaxAge(days: 30)); } if (!siteOk) { app.Run(async context => await context.Response.WriteAsync(siteError)); return; } var options = new RewriteOptions() .AddIISUrlRewrite(env.ContentRootFileProvider, IISUrlRewriteConfigPath); app.UseRewriter(options); app.UseRouting(); //if you've configured it at /blog or /whatever, set that pathbase so ~ will generate correctly var rootUri = new Uri(dasBlogSettings.SiteConfiguration.Root); var path = rootUri.AbsolutePath; //Deal with path base and proxies that change the request path if (path != "/") { app.Use((context, next) => { context.Request.PathBase = new PathString(path); return(next.Invoke()); }); } app.UseForwardedHeaders(); app.UseStaticFiles(); app.UseCookiePolicy(); Action <StaticFileResponseContext> cacheControlPrepResponse = (ctx) => { const int durationInSeconds = 60 * 60 * 24; ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=" + durationInSeconds; ctx.Context.Response.Headers["Expires"] = DateTime.UtcNow.AddHours(12).ToString("R"); }; app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(BinariesPath), RequestPath = string.Format("/{0}", BinariesUrlRelativePath), OnPrepareResponse = cacheControlPrepResponse }); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(BinariesPath), RequestPath = string.Format("/{0}", BinariesUrlRelativePath), OnPrepareResponse = cacheControlPrepResponse }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "content/radioStories")), RequestPath = "/content/radioStories", OnPrepareResponse = cacheControlPrepResponse }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Themes")), RequestPath = "/theme", OnPrepareResponse = cacheControlPrepResponse }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Themes")), RequestPath = "/themes", OnPrepareResponse = cacheControlPrepResponse }); app.UseAuthentication(); app.Use(PopulateThreadCurrentPrincipalForMvc); app.UseRouting(); app.UseAuthorization(); app.UseXContentTypeOptions(); app.UseXXssProtection(options => options.EnabledWithBlockMode()); app.UseXfo(options => options.SameOrigin()); app.UseReferrerPolicy(opts => opts.NoReferrerWhenDowngrade()); var SecurityScriptSources = Configuration.GetSection("SecurityScriptSources")?.Value?.Split(";"); var SecurityStyleSources = Configuration.GetSection("SecurityStyleSources")?.Value?.Split(";"); if (SecurityStyleSources != null && SecurityScriptSources != null) { app.UseCsp(options => options .DefaultSources(s => s.Self() .CustomSources("data:") .CustomSources("https:")) .StyleSources(s => s.Self() .CustomSources(SecurityStyleSources) .UnsafeInline() ) .ScriptSources(s => s.Self() .CustomSources(SecurityScriptSources) .UnsafeInline() .UnsafeEval() ) ); } app.Use(async(context, next) => { //w3c draft context.Response.Headers.Add("Feature-Policy", "geolocation 'none';midi 'none';sync-xhr 'none';microphone 'none';camera 'none';magnetometer 'none';gyroscope 'none';fullscreen 'self';payment 'none';"); //being renamed/changed to this soon context.Response.Headers.Add("Permissions-Policy", "geolocation=(),midi=(),sync-xhr=(),microphone=(),camera=(),magnetometer=(),gyroscope=(),fullscreen=(self),payment=()"); await next.Invoke(); }); app.UseLoggingAgent(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/healthcheck"); if (dasBlogSettings.SiteConfiguration.EnableTitlePermaLinkUnique) { endpoints.MapControllerRoute( "Original Post Format", "~/{year:int}/{month:int}/{day:int}/{posttitle}.aspx", new { controller = "BlogPost", action = "Post", posttitle = "" }); endpoints.MapControllerRoute( "New Post Format", "~/{year:int}/{month:int}/{day:int}/{posttitle}", new { controller = "BlogPost", action = "Post", postitle = "" }); } else { endpoints.MapControllerRoute( "Original Post Format", "~/{posttitle}.aspx", new { controller = "BlogPost", action = "Post", posttitle = "" }); endpoints.MapControllerRoute( "New Post Format", "~/{posttitle}", new { controller = "BlogPost", action = "Post", postitle = "" }); } endpoints.MapControllerRoute( name: "default", "~/{controller=Home}/{action=Index}/{id?}"); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions <RouteOptions> routeOptionsAccessor) { (var siteOk, string siteError) = RepairSite(app); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/home/error"); } if (!siteOk) { app.Run(async context => await context.Response.WriteAsync(siteError)); return; } app.Use((context, next) => { return(next()); }); app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(GetDataRoot(env), binariesPath.TrimStart('/'))), RequestPath = binariesPath }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Themes")), RequestPath = "/theme" }); var options = new RewriteOptions() .AddIISUrlRewrite(env.ContentRootFileProvider, @"Config/IISUrlRewrite.xml"); app.UseRewriter(options); app.UseAuthentication(); app.Use(PopulateThreadCurrentPrincipalForMvc); app.UseMvc(routes => { if (routeOptionsAccessor.Value.EnableTitlePermaLinkUnique) { routes.MapRoute( "Original Post Format", "{year:int}/{month:int}/{day:int}/{posttitle}.aspx", new { controller = "BlogPost", action = "Post", posttitle = "" }); routes.MapRoute( "New Post Format", "{year:int}/{month:int}/{day:int}/{posttitle}", new { controller = "BlogPost", action = "Post", postitle = "" }); } else { routes.MapRoute( "Original Post Format", "{posttitle}.aspx", new { controller = "BlogPost", action = "Post", posttitle = "" }); routes.MapRoute( "New Post Format", "{posttitle}", new { controller = "BlogPost", action = "Post", postitle = "" }); } routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public static RewriteOptions AddRedirectToApex(this RewriteOptions options) { options.Rules.Add(new RedirectToApexRule()); return(options); }
public static RewriteOptions AddRedirectToProxiedHttps(this RewriteOptions options) { options.Rules.Add(new RedirectToProxiedHttpsRule()); return(options); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// all configured methods are ran at every request /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error/500"); } // Rewrite webforms urls from old versions to urls for this version. We do that using a redirect and not a rewrite, as // these urls should be replaced, so we need the client to know about the new url in the address bar (if applicable). // One thing to understand is that the regex is only applied on the *path* of the URL. If you include query elements in the regex, // it won't match. This requires the specific controller actions we've added to deal with the query arguments. var redirectOptions = new RewriteOptions() .AddRedirect("^default.aspx", "Home", (int)HttpStatusCode.PermanentRedirect) .AddRedirect("^[gG]oto[mM]essage.aspx(.*)", "Message/OldGoto/$1", (int)HttpStatusCode.PermanentRedirect) .AddRedirect("^[rR]ss[fF]orum.aspx(.*)", "RssForum/Old/$1", (int)HttpStatusCode.PermanentRedirect) .AddRedirect("^[mM]essages.aspx(.*)", "Thread/Old/$1", (int)HttpStatusCode.PermanentRedirect) .AddRedirect("^[sS]earch[uU]nattended.aspx(.*)", "SearchUnattended/$1", (int)HttpStatusCode.PermanentRedirect); app.UseRewriter(redirectOptions); app.UseHttpsRedirection(); app.UseStaticFiles(); app.Use(async(context, next) => { await next(); if (context.Response.StatusCode == 404 && !context.Response.HasStarted) { //Re-execute the request so the user gets the error page string originalPath = context.Request.Path.Value; context.Items["originalPath"] = originalPath; context.Request.Path = "/Error/404"; // call next in pipeline await next(); } }); // If the database is empty, we have to redirect to the initialization page. app.Use(async(context, next) => { await Startup.RedirectToInitIfRequired(context); // call next in pipeline await next(); }); app.UseRouting(); app.UseResponseCaching(); app.UseAuthentication(); app.UseAuthorization(); app.UseIPFilter(); app.UseSession(); // own middleware function to initialize session if required. app.Use(async(context, next) => { await Startup.InitializeSessionIfRequiredAsync(context); await Startup.LogOutIfNeeded(context); // call next in pipeline await next(); }); // last element added to the chain. app.UseEndpoints(endpoints => RegisterRoutes(endpoints)); // HnD one-time configuration now we now the environment. HnDConfiguration.Current.LoadStaticData(env.WebRootPath, env.ContentRootPath); }
public static int Main(string[] _args) { try { var options = new RewriteOptions(); foreach (var arg in _args) { ParseArgument(arg, options); } var argv = _args.Where(arg => !arg.StartsWith("-")).ToArray(); var step = (options.Overwrite || options.Audit) ? 1 : 2; if (argv.Length < step) { Usage(); return(1); } int exitCode = 0; for (int i = 0; i < argv.Length; i += step) { var src = argv[i]; var dst = options.Overwrite || options.Audit ? src : argv[i + 1]; if (options.Audit) { Console.WriteLine($"// {src}{Environment.NewLine}===="); } else if (options.Verbose) { Console.WriteLine($"// {Path.GetFileName (src)} -> {Path.GetFullPath (dst)}...{Environment.NewLine}===="); } else if (argv.Length > step) { Console.WriteLine($"// {Path.GetFileName (src)} -> {Path.GetFullPath (dst)}"); } var wroteOk = false; try { var assemblyResolver = new DefaultAssemblyResolver(); assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(src)); using (var def = AssemblyDefinition.ReadAssembly(src, new ReaderParameters { ReadWrite = options.Overwrite, ReadingMode = ReadingMode.Deferred, AssemblyResolver = assemblyResolver, ReadSymbols = options.EnableSymbols, SymbolReaderProvider = new DefaultSymbolReaderProvider(throwIfNoSymbol: false) })) { var arw = new AssemblyRewriter(def, options); int errorCount = arw.Rewrite(); if (options.Mark) { def.Name.Name = Path.GetFileNameWithoutExtension(dst); } if (!options.Audit) { if (errorCount > 0 && false) { Console.Error.WriteLine($"// Not saving due to error(s): {dst}"); exitCode += 1; } else { var shouldWriteSymbols = options.EnableSymbols && def.MainModule.SymbolReader != null; if (options.Overwrite) { def.Write(); } else { def.Write(dst + ".tmp", new WriterParameters { WriteSymbols = shouldWriteSymbols, DeterministicMvid = true }); } wroteOk = true; } } } } catch (Exception exc) { Console.Error.WriteLine("Unhandled exception while rewriting {0}. Continuing...", src); Console.Error.WriteLine(exc); exitCode += 1; } if (wroteOk && !options.Overwrite) { File.Copy(dst + ".tmp", dst, true); if (File.Exists(dst + ".pdb")) { File.Copy(dst + ".pdb", dst.Replace(".exe", ".pdb"), true); File.Delete(dst + ".pdb"); } File.Delete(dst + ".tmp"); } } return(exitCode); } finally { if (Debugger.IsAttached) { Console.WriteLine("Press enter to exit"); Console.ReadLine(); } } }
// 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" }); }); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime events) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } var options = new RewriteOptions() .AddRedirectToHttps(); //app.UseRewriter(options); events.ApplicationStarted.Register(state => { //application started var appParameter = state as IApplicationBuilder; }, app); events.ApplicationStopping.Register( callback: state => { //application is stopping }, state: "some state"); app.UseStaticFiles(new StaticFileOptions { RequestPath = "/resources", FileProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly()) }); app.UseStaticFiles(new StaticFileOptions { RequestPath = "/files", FileProvider = new PhysicalFileProvider(Path.GetFullPath("wwwroot")), OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Add("X-SENDER", "ASP.NET Core"); } }); app.UseDefaultFiles(new DefaultFilesOptions { DefaultFileNames = new[] { "document.html" }, RequestPath = "/files", FileProvider = new PhysicalFileProvider(Path.GetFullPath("wwwroot")), }); /*var provider = new FileExtensionContentTypeProvider(); * provider.Mappings[".text"] = "text/plain"; * * app.UseStaticFiles(new StaticFileOptions * { * ContentTypeProvider = provider, * DefaultContentType = "text/plain", * ServeUnknownFileTypes = true * });*/ app.UseDirectoryBrowser("/files"); app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = "/resources", FileProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly()) }); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); endpoints.MapControllerRoute("areas", "{area:exists}/{controller=Home}/{action=Index}"); endpoints.MapGrpcService <PingPongService>(); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions <RouteOptions> routeOptionsAccessor, IDasBlogSettings dasBlogSettings) { (var siteOk, string siteError) = RepairSite(app); if (env.IsDevelopment() || env.IsStaging()) { app.UseDeveloperExceptionPage(); //app.UseBrowserLink(); } else { app.UseExceptionHandler("/home/error"); } if (!siteOk) { app.Run(async context => await context.Response.WriteAsync(siteError)); return; } var options = new RewriteOptions() .AddIISUrlRewrite(env.ContentRootFileProvider, IISUrlRewriteConfigPath); app.UseRewriter(options); app.UseRouting(); //if you've configured it at /blog or /whatever, set that pathbase so ~ will generate correctly Uri rootUri = new Uri(dasBlogSettings.SiteConfiguration.Root); string path = rootUri.AbsolutePath; //Deal with path base and proxies that change the request path //https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.2#deal-with-path-base-and-proxies-that-change-the-request-path if (path != "/") { app.Use((context, next) => { context.Request.PathBase = new PathString(path); return(next.Invoke()); }); } app.UseForwardedHeaders(); app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(GetDataRoot(env), BinariesPath.TrimStart('/'))), RequestPath = BinariesPath }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Themes")), RequestPath = "/theme" }); app.UseAuthentication(); app.Use(PopulateThreadCurrentPrincipalForMvc); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/healthcheck"); if (routeOptionsAccessor.Value.EnableTitlePermaLinkUnique) { endpoints.MapControllerRoute( "Original Post Format", "~/{year:int}/{month:int}/{day:int}/{posttitle}.aspx", new { controller = "BlogPost", action = "Post", posttitle = "" }); endpoints.MapControllerRoute( "New Post Format", "~/{year:int}/{month:int}/{day:int}/{posttitle}", new { controller = "BlogPost", action = "Post", postitle = "" }); } else { endpoints.MapControllerRoute( "Original Post Format", "~/{posttitle}.aspx", new { controller = "BlogPost", action = "Post", posttitle = "" }); endpoints.MapControllerRoute( "New Post Format", "~/{posttitle}", new { controller = "BlogPost", action = "Post", postitle = "" }); } endpoints.MapControllerRoute( name: "default", "~/{controller=Home}/{action=Index}/{id?}"); }); }
// 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.UseStaticFiles(); app.UseSession(); //Eksempel på rewriting var options = new RewriteOptions() .AddRewrite("NewUser", "/UserRegistration/Index", false); app.UseRewriter(options); //Why would you want this here? 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 sucessfully created.")); }); var newUserRoutes = routeBuilder.Build(); app.UseRouter(newUserRoutes); app.UseWebSockets(); app.UseCommunicationMiddleware(); //Use localization var supportedCultures = CultureInfo.GetCultures(CultureTypes.AllCultures); var localizationOptions = new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }; localizationOptions.RequestCultureProviders.Clear(); localizationOptions.RequestCultureProviders.Add(new CultureProviderResolverService()); app.UseRequestLocalization(localizationOptions); //Use the MVC model 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}"); }
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 }); }); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app">The application builder.</param> /// <param name="env">The hosting environment.</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSpaStaticFiles(); this.startupConfig.UseForwardHeaders(app); this.startupConfig.UseSwagger(app); this.startupConfig.UseHttp(app); this.startupConfig.UseContentSecurityPolicy(app); this.startupConfig.UseAuth(app); 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(); } if (!env.IsDevelopment()) { app.UseResponseCompression(); } app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); if (env.IsDevelopment() && Debugger.IsAttached) { endpoints.MapToVueCliProxy( "{*path}", new SpaOptions { SourcePath = "ClientApp" }, npmScript: "serve", port: 8585, regex: "Compiled ", forceKill: true); } }); bool redirectToWWW = this.configuration.GetSection("WebClient").GetValue <bool>("RedirectToWWW"); if (redirectToWWW) { RewriteOptions rewriteOption = new RewriteOptions() .AddRedirectToWwwPermanent(); app.UseRewriter(rewriteOption); } app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment() && !Debugger.IsAttached) { // change this to whatever webpack dev server says it's running on spa.UseProxyToSpaDevelopmentServer("http://localhost:8080"); } }); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = (content) => { var headers = content.Context.Response.Headers; var contentType = headers["Content-Type"]; if (contentType != "application/x-gzip" && !content.File.Name.EndsWith(".gz", StringComparison.CurrentCultureIgnoreCase)) { return; } var mimeTypeProvider = new FileExtensionContentTypeProvider(); var fileNameToTry = content.File.Name.Substring(0, content.File.Name.Length - 3); if (mimeTypeProvider.TryGetContentType(fileNameToTry, out var mimeType)) { headers.Add("Content-Encoding", "gzip"); headers["Content-Type"] = mimeType; } }, });
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // Note: health checks come before HTTPS redirection so we get a 200 even on HTTP. app.UseHealthChecks("/healthz"); StackdriverOptions.Configure(app, env, loggerFactory); NetworkOptions.Configure(app, env); app.UseSingleLineResponseLogging(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseDefaultFiles(); // Default content, e.g. CSS. // Even though we don't normally host the nzd files locally, it's useful to be able // to in case of emergency. app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = new FileExtensionContentTypeProvider { Mappings = { [".nzd"] = "application/octet-stream" } }, OnPrepareResponse = context => SetCacheControlHeaderForStaticContent(env, context.Context) }); // API documentation app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "docfx")), ContentTypeProvider = new FileExtensionContentTypeProvider { Mappings = { [".yml"] = "text/x-yaml" } }, OnPrepareResponse = context => SetCacheControlHeaderForStaticContent(env, context.Context) }); // Captures "unstable" or a specific version - used several times below. string anyVersion = @"((?:1\.[0-4]\.x)|(?:unstable)|(?:2\.[0-4]\.x))"; var rewriteOptions = new RewriteOptions() // Docfx wants index.html to exist, which is annoying... just redirect. .AddRedirect($@"^index.html$", "/") // We don't have an index.html or equivalent for the APIs, so let's go to NodaTime.html .AddRedirect($@"^{anyVersion}/api/?$", "$1/api/NodaTime.html") // Compatibility with old links .AddRedirect($@"^{anyVersion}/userguide/([^.]+)\.html$", "$1/userguide/$2") .AddRedirect($@"^developer/([^.]+)\.html$", "developer/$1") // Avoid links from userguide/unstable from going to userguide/core-concepts etc // (There are no doubt better ways of doing this...) .AddRedirect($@"^{anyVersion}/userguide$", "$1/userguide/") .AddRedirect($@"^developer$", "developer/") // Make /api and /userguide links to the latest stable release. .AddRedirect("^(api|userguide)(/.*)?$", "2.4.x/$1$2"); app.UseRewriter(rewriteOptions); // At some stage we may want an MVC view for the home page, but at the moment // we're just serving static files, so we don't need much. app.UseMvc(routes => { // TODO: Find a better way of routing. This is pretty nasty. routes.MapRoute("Developer docs", "developer/{*url}", new { controller = "Documentation", bundle = "developer", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("1.0.x user guide", "1.0.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.0.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("1.1.x user guide", "1.1.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.1.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("1.2.x user guide", "1.2.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.2.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("1.3.x user guide", "1.3.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.3.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("1.4.x user guide", "1.4.x/userguide/{*url}", new { controller = "Documentation", bundle = "1.4.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("2.0.x user guide", "2.0.x/userguide/{*url}", new { controller = "Documentation", bundle = "2.0.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("2.1.x user guide", "2.1.x/userguide/{*url}", new { controller = "Documentation", bundle = "2.1.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("2.2.x user guide", "2.2.x/userguide/{*url}", new { controller = "Documentation", bundle = "2.2.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("2.3.x user guide", "2.3.x/userguide/{*url}", new { controller = "Documentation", bundle = "2.3.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("2.4.x user guide", "2.4.x/userguide/{*url}", new { controller = "Documentation", bundle = "2.4.x", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("Unstable user guide", "unstable/userguide/{*url}", new { controller = "Documentation", bundle = "unstable", action = nameof(DocumentationController.ViewDocumentation) }); routes.MapRoute("default", "{action=Index}/{id?}", new { controller = "Home" }); }); // Force all the Markdown to be loaded on startup. app.ApplicationServices.GetRequiredService <MarkdownLoader>(); // Force the set of releases to be first loaded on startup. app.ApplicationServices.GetRequiredService <IReleaseRepository>().GetReleases(); // Force the set of benchmarks to be first loaded on startup. app.ApplicationServices.GetRequiredService <IBenchmarkRepository>().ListEnvironments(); // Force the set of TZDB data to be first loaded on startup. app.ApplicationServices.GetRequiredService <ITzdbRepository>().GetReleases(); #if BLAZOR app.Map("/blazor", child => child.UseBlazor <NodaTime.Web.Blazor.Program>()); #endif }
// 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.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } // app.UseStatusCodePages(); // Status Code: 404; Not Found // app.UseStatusCodePages("text/plain", "Status code page, status code: {0}"); // app.UseStatusCodePages(async context => // { // context.HttpContext.Response.ContentType = "text/plain"; // await context.HttpContext.Response.WriteAsync( // "Status code page, status code: " + // context.HttpContext.Response.StatusCode); // }); app.UseStatusCodePagesWithReExecute("/Home/Error/{0}"); app.UseHttpsRedirection(); // Demo Redirect vs Rewrite // https://docs.microsoft.com/en-gb/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-2.2 // https://tahirnaushad.com/2017/08/18/url-rewriting-in-asp-net-core/ // Redirect: Server responds with status code 301 (Moved Permanently) or 302 (Found) with new Location header, instructing client to request the new location e.g. /movies // Rewrite: Server will internally map to new location e.g. /stars and return 200 (OK). var rewrite = new RewriteOptions() .AddRedirect("films", "movies") .AddRewrite("actors", "stars", true); app.UseRewriter(rewrite); app.UseStaticFiles(); app.UseCookiePolicy(); // Use authentication app.UseAuthentication(); // app.UseJwtBearerAuthentication(new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions() { // Audience = "http://localhost:5001/", // Authority = "http://localhost:5000/", // AutomaticAuthenticate = true // }); app.UseMvc(routes => { // Add default routes for area handling routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public static RewriteOptions AddRedirectToLowercaseTrailingSlash(this RewriteOptions options) => AddRedirectToLowercaseTrailingSlash(options, (request) => true, StatusCodes.Status301MovedPermanently);
/// <summary> /// Configure service /// </summary> /// <param name="app">Application</param> /// <param name="env">Enviroment</param> /// <param name="loggerFactory">Logger factory</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); if (Environment.GetEnvironmentVariable("ASPNETCORE_RUNTYPE_ENVIRONMENT") == "Docker") { loggerFactory.AddLog4Net("log4netDocker.config"); } else { loggerFactory.AddLog4Net("log4net.config"); } ServiceActivator.Configure(app.ApplicationServices); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseIpRateLimiting(); app.UseStatusCodePages(); app.UseStaticFiles(); app.UseSwagger(swagger => { swagger.PreSerializeFilters.Add((swaggerDoc, httpReq) => { swaggerDoc.Servers = new List <OpenApiServer> { new OpenApiServer { Url = $"{SwaggerConfiguration.Host}/{SwaggerConfiguration.HostPostfix}" } }; }); swagger.RouteTemplate = $"/{SwaggerConfiguration.PrefixDocPath}/{{documentname}}/swagger.json"; }); app.UseSwaggerUI(swaggerUI => { string hostPrefix = string.IsNullOrEmpty(SwaggerConfiguration.HostPostfix) ? string.Empty : "/" + SwaggerConfiguration.HostPostfix; swaggerUI.SwaggerEndpoint($"{hostPrefix}/{SwaggerConfiguration.PrefixDocPath}/{SwaggerConfiguration.Version}/swagger.json", SwaggerConfiguration.Title); swaggerUI.RoutePrefix = SwaggerConfiguration.PrefixDocPath; }); app.UseRouting(); app.UseMiddleware <ExceptionMiddleware>(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); app.UseCors(_allowSpecificOrigins); var option = new RewriteOptions(); option.AddRedirect("^$", $"{SwaggerConfiguration.HostPostfix}/swagger/index.html"); app.UseRewriter(option); }