// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostEnvironment env, ConfigurationsService configurations) { // Use static files app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", "public, max-age=604800"); } }); // Uses routes app.UseRouting(); // Cors app.UseCors("Travian"); // Uses authentication app.UseAuthentication(); // Use authorization app.UseAuthorization(); // Uses session app.UseSession(); // Session handler app.UseMiddleware <SessionHandler>(); if (_isProduction) { // Show errors in page app.UseHsts(); // Error Handling app.UseStatusCodePages(); // Redirect options (www and https) var rewriteOptions = new RewriteOptions(); if (configurations.RedirectWww) { rewriteOptions.AddRedirectToWwwPermanent(); } if (configurations.RedirectHttps) { app.UseHttpsRedirection(); rewriteOptions.AddRedirectToHttpsPermanent(); } app.UseRewriter(rewriteOptions); } else { app.UseDeveloperExceptionPage(); } app.UseMiddleware <RedirectHandler>(); // Map routes app.UseEndpoints(endpoints => endpoints.MapControllers()); }
public static IApplicationBuilder UseConfiguredRewriter(this IApplicationBuilder app) { var options = new RewriteOptions(); options.AddRedirectToHttpsPermanent(); options.AddRedirectToWwwPermanent(); return(app.UseRewriter(options)); }
public void Configure(IApplicationBuilder app) { if (Env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Blog/Error"); app.UseHsts(); } var rewriteOptions = new RewriteOptions(); if (Configuration.GetValue <bool>("forceSsl")) { rewriteOptions.AddRedirectToHttpsPermanent(); } if (Configuration.GetValue <bool>("forceWwwPrefix")) { rewriteOptions.AddRedirectToWwwPermanent(); } app.UseRewriter(rewriteOptions); app.UseStaticFiles(); app.UseCookiePolicy(new CookiePolicyOptions()); app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Blog}/{action=Index}"); endpoints.MapControllerRoute( name: "post", pattern: "blog/post/{id}", defaults: new { controller = "Blog", action = "Post" }); endpoints.MapControllerRoute( name: "postEdit", pattern: "blog/editpost/{id?}", defaults: new { controller = "Blog", action = "EditPost" }); endpoints.MapControllerRoute( name: "postEdit", pattern: "blog/category/{name}", defaults: new { controller = "Blog", action = "Category" }); }); }
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); AppDomain.CurrentDomain.UnhandledException += AppDomain_OnUnhandledException; AppDomain.CurrentDomain.AssemblyResolve += AppDomain_OnAssemblyResolve; 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); app.UseBindKraftLogger(env, loggerFactory, ERRORURLSEGMENT); app.UseBindKraftProfiler(env, loggerFactory, _MemoryCache); 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 foreach (string dir in _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders) { if (!Directory.Exists(dir)) { throw new Exception($"No \"{dir}\" directory found! The CoreKraft initialization cannot continue."); } } string kraftUrlSegment = _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlSegment; try { KraftModuleCollection modulesCollection = app.ApplicationServices.GetService <KraftModuleCollection>(); Dictionary <string, string> moduleKey2Path = new Dictionary <string, string>(); IApplicationLifetime applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>(); lock (_SyncRoot) { foreach (string dir in _KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolders) { string[] moduleDirectories = Directory.GetDirectories(dir); foreach (string subdirectory in moduleDirectories) { DirectoryInfo moduleDirectory = new DirectoryInfo(subdirectory); if (moduleDirectory.Name != null && moduleDirectory.Name.Equals("_PluginsReferences", StringComparison.InvariantCultureIgnoreCase)) { continue; } ICachingService cachingService = app.ApplicationServices.GetService <ICachingService>(); KraftModule kraftModule = modulesCollection.GetModule(moduleDirectory.Name); if (kraftModule != null) { continue; } kraftModule = modulesCollection.RegisterModule(dir, moduleDirectory.Name, cachingService); if (kraftModule == null || !kraftModule.IsInitialized) { _Logger.LogInformation($"Module not created for directory \"{moduleDirectory.Name}\" because of missing configuration files."); continue; } KraftStaticFiles.RegisterStaticFiles(app, moduleDirectory.FullName, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModuleImages); KraftStaticFiles.RegisterStaticFiles(app, moduleDirectory.FullName, kraftUrlSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlResourceSegment, _KraftGlobalConfigurationSettings.GeneralSettings.KraftUrlModulePublic); moduleKey2Path.Add(kraftModule.Key.ToLower(), dir); //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(dir, kraftModule.Key); 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(); _KraftGlobalConfigurationSettings.GeneralSettings.ModuleKey2Path = moduleKey2Path; } 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) { 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)); 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); }
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); }