예제 #1
0
        private void ConfigureLogging(
            ILoggerFactory loggerFactory,
            IServiceProvider serviceProvider
            , cloudscribe.Logging.Web.ILogRepository logRepo
            )
        {
            // a customizable filter for logging
            LogLevel minimumLevel = LogLevel.Information;

            // add exclusions to remove noise in the logs
            var excludedLoggers = new List <string>
            {
                "Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware",
                "Microsoft.AspNetCore.Hosting.Internal.WebHost",
            };

            Func <string, LogLevel, bool> logFilter = (string loggerName, LogLevel logLevel) =>
            {
                if (logLevel < minimumLevel)
                {
                    return(false);
                }

                if (excludedLoggers.Contains(loggerName))
                {
                    return(false);
                }

                return(true);
            };

            loggerFactory.AddDbLogger(serviceProvider, logFilter, logRepo);
        }
예제 #2
0
        public void Configure(
            ILoggerFactory loggerFactory,
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            loggerFactory.AddDbLogger(serviceProvider: app.ApplicationServices, minLevel: LogLevel.Warning);

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

            // Serve wwwroot as root
            app.UseFileServer(new FileServerOptions
            {
                // Don't expose file system
                EnableDirectoryBrowsing = false
            });

            // Adds all of the ASP.NET Core Identity related initializations at once.
            app.UseCustomIdentityServices();

            // app.UseNoBrowserCache();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Account}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
예제 #3
0
        private void ConfigureLogging(ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {
            //var logRepository = serviceProvider.GetService<cloudscribe.Logging.Web.ILogRepository>();

            loggerFactory.AddConsole(minLevel: LogLevel.Warning);

            // a customizable filter for logging
            LogLevel minimumLevel = LogLevel.Warning;

            // add exclusions to remove noise in the logs
            var excludedLoggers = new List <string>
            {
                "Microsoft.Data.Entity.Storage.Internal.RelationalCommandBuilderFactory",
                "Microsoft.Data.Entity.Query.Internal.QueryCompiler",
                "Microsoft.Data.Entity.DbContext",
            };

            Func <string, LogLevel, bool> logFilter = (string loggerName, LogLevel logLevel) =>
            {
                if (logLevel < minimumLevel)
                {
                    return(false);
                }

                if (excludedLoggers.Contains(loggerName))
                {
                    return(false);
                }

                return(true);
            };

            loggerFactory.AddDbLogger(serviceProvider, logFilter);
        }
예제 #4
0
        private static void ConfigureLogging(
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            IServiceProvider serviceProvider
            )
        {
            LogLevel minimumLevel;

            if (env.IsProduction())
            {
                minimumLevel = LogLevel.Warning;
            }
            else
            {
                minimumLevel = LogLevel.Information;
            }

            var logRepo = serviceProvider.GetService <cloudscribe.Logging.Web.ILogRepository>();

            // a customizable filter for logging
            // add exclusions to remove noise in the logs
            var excludedLoggers = new List <string>
            {
                "Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware",
                "Microsoft.AspNetCore.Hosting.Internal.WebHost",
            };

            Func <string, LogLevel, bool> logFilter = (string loggerName, LogLevel logLevel) =>
            {
                if (logLevel < minimumLevel)
                {
                    return(false);
                }

                if (excludedLoggers.Contains(loggerName))
                {
                    return(false);
                }

                return(true);
            };

            loggerFactory.AddDbLogger(serviceProvider, logFilter, logRepo);
        }
        public void Configure(ILoggerFactory loggerFactory, IApplicationBuilder app, IHostingEnvironment env)
        {
            try
            {
                loggerFactory.AddLog4Net();
                loggerFactory.AddDbLogger(serviceProvider: app.ApplicationServices, scopeFactory: app.ApplicationServices.GetRequiredService <IServiceScopeFactory>(), minLevel: LogLevel.Warning);
                app.UseGlobalExceptionHandler(loggerFactory);

                app.UseAngularAntifCityeryToken();

                app.UseAuthentication();



                app.UseFileServer();

                app.UseResponseCompression();


                app.UseSwagger();

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/V1/swagger.json", "MSHB.Reservation API V1");
                });

                app.UseStatusCodePages();
                app.UseDefaultFiles(); // so index.html is not required
                app.UseStaticFiles();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public void Configure(ILoggerFactory loggerFactory, IApplicationBuilder app)
        {
            try
            {
                app.UseResponseCompression();

                loggerFactory.AddLog4Net();
                loggerFactory.AddDbLogger(serviceProvider: app.ApplicationServices, scopeFactory: app.ApplicationServices.GetRequiredService <IServiceScopeFactory>(), minLevel: LogLevel.Warning);
                app.UseGlobalExceptionHandler(loggerFactory);

                app.UseFileServer();
                app.UseResponseCompression();

                //app.UseSwagger();
                //app.UseSwaggerUI(c =>
                //{
                //    c.SwaggerEndpoint("/swagger/V1/swagger.json", "MSHB.StockAssistanceProvider API V1");
                //});

                app.UseStatusCodePages();
                app.UseDefaultFiles(); // so index.html is not required
                app.UseStaticFiles();
                app.UseRouting();
                app.UseCors();

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

                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
예제 #7
0
        public void Configure(
            ILoggerFactory loggerFactory,
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            loggerFactory.AddDbLogger(serviceProvider: app.ApplicationServices, minLevel: LogLevel.Warning);

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

            // Serve wwwroot as root
            app.UseFileServer();

            app.UseFileServer(new FileServerOptions
            {
                // Set root of file server
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "bower_components")),
                // Only react to requests that match this path
                RequestPath = "/bower_components",
                // Don't expose file system
                EnableDirectoryBrowsing = false
            });

            // Adds all of the ASP.NET Core Identity related initializations at once.
            app.UseCustomIdentityServices();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Account}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
예제 #8
0
        private static void ConfigureLogging(
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            IServiceProvider serviceProvider,
            IConfiguration config
            )
        {
            LogLevel minimumLevel;
            string   levelConfig;

            if (env.IsProduction())
            {
                levelConfig = config["AppSettings:ProductionLogLevel"];
            }
            else
            {
                levelConfig = config["AppSettings:DevLogLevel"];
            }
            switch (levelConfig)
            {
            case "Debug":
                minimumLevel = LogLevel.Debug;
                break;

            case "Information":
                minimumLevel = LogLevel.Information;
                break;

            case "Trace":
                minimumLevel = LogLevel.Trace;
                break;

            default:
                minimumLevel = LogLevel.Warning;
                break;
            }

            // a customizable filter for logging
            // add exclusions to remove noise in the logs
            var excludedLoggers = new List <string>
            {
                "Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware",
                "Microsoft.AspNetCore.Hosting.Internal.WebHost",
            };

            Func <string, LogLevel, bool> logFilter = (string loggerName, LogLevel logLevel) =>
            {
                if (logLevel < minimumLevel)
                {
                    return(false);
                }

                if (excludedLoggers.Contains(loggerName))
                {
                    return(false);
                }

                return(true);
            };

            loggerFactory.AddDbLogger(serviceProvider, logFilter);
        }
예제 #9
0
        // Configure is called after ConfigureServices is called.
        // you can change this method signature to include any dependencies that need to be injected into this method
        // you can see we added the dependency for IOptions<MultiTenantOptions>
        // so basically if you need any service in this method that was previously setup in ConfigureServices
        // you can just add it to the method signature and it will be provided by dependency injection
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            IOptions <MultiTenantOptions> multiTenantOptions,
            IServiceProvider serviceProvider,
            ILogRepository logRepository)
        {
            // Configure the HTTP request pipeline.

            //http://blog.getglimpse.com/2015/11/19/installing-glimpse-v2-beta1/
            bool enableGlimpse = Configuration.Get <bool>("DiagnosticOptions:EnableGlimpse", false);

            if (enableGlimpse)
            {
                app.UseGlimpse();
            }


            // LogLevels
            //Debug = 1,
            //Trace = 2,
            //Information = 3,
            //Warning = 4,
            //Error = 5,
            //Critical = 6,

            // Add the console logger.
            loggerFactory.AddConsole(minLevel: LogLevel.Warning);

            // a customizable filter for logging
            LogLevel      minimumLevel    = LogLevel.Warning;
            List <string> excludedLoggers = new List <string>();

            // add exclusions to remove noise in the logs

            // we need to filter out EF otherwise each time we persist a log item to the db more logs are generated
            // so it can become an infinite loop that keeps creating data
            // you can add any loggers that you want to exclude to reduce noise in the log
            excludedLoggers.Add("Microsoft.Data.Entity.Storage.Internal.RelationalCommandBuilderFactory");
            excludedLoggers.Add("Microsoft.Data.Entity.Query.Internal.QueryCompiler");
            excludedLoggers.Add("Microsoft.Data.Entity.DbContext");

            Func <string, LogLevel, bool> logFilter = delegate(string loggerName, LogLevel logLevel)
            {
                if (logLevel < minimumLevel)
                {
                    return(false);
                }
                if (excludedLoggers.Contains(loggerName))
                {
                    return(false);
                }

                return(true);
            };

            // Add cloudscribe db logging
            loggerFactory.AddDbLogger(serviceProvider, logRepository, logFilter);



            //app.UseCultureReplacer();

            // localization from .resx files is not really working in beta8
            // will have to wait till next release

            var supportedCultures = new[]
            {
                new CultureInfo("en-US"),
                new CultureInfo("it"),
                new CultureInfo("fr-FR")
            };

            var locOptions = new RequestLocalizationOptions
            {
                // You must explicitly state which cultures your application supports.
                // These are the cultures the app supports for formatting numbers, dates, etc.
                SupportedCultures   = supportedCultures,
                SupportedUICultures = supportedCultures
            };

            // You can change which providers are configured to determine the culture for requests, or even add a custom
            // provider with your own logic. The providers will be asked in order to provide a culture for each request,
            // and the first to provide a non-null result that is in the configured supported cultures list will be used.
            // By default, the following built-in providers are configured:
            // - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing
            // - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie
            // - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header
            //locOptions.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
            //{
            //  // My custom request culture logic
            //  return new ProviderCultureResult("en");
            //}));
            //app.UseRequestLocalization(locOptions,
            //    defaultRequestCulture: new RequestCulture(culture: "en-US", uiCulture: "en-US"));


            // Add the following to the request pipeline only in development environment.
            if (env.IsEnvironment("Development"))
            {
                //app.UseBrowserLink();

                app.UseDeveloperExceptionPage();

                //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                // handle 404 and other non success
                //app.UseStatusCodePages();

                // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
                // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
                // app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
                // app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
                // app.UseStatusCodePages(builder => builder.UseWelcomePage());
                //app.UseStatusCodePagesWithReExecute("/errors/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }

            // Add the platform handler to the request pipeline.
            //app.UseIISPlatformHandler();
            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            //app.UseRuntimeInfoPage("/info");

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // the only thing we are using session for is Alerts
            app.UseSession();
            //app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(20));

            app.UseMultitenancy <SiteSettings>();

            // this is in Startup.CloudscribeCore.cs
            app.UseCloudscribeCore(multiTenantOptions, Configuration);

            // it is very important that all authentication configuration be set before configuring mvc
            // ie if app.UseFacebookAuthentication(); was below app.UseMvc the facebook login button will not be shown


            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                // Understanding ASP.NET Routing:

                // it is very important that routes are registered in the correct order. more specific routes must be registered first and
                // less specific routes must be registered later. a request may match more than one route.

                // When a request comes in it is compared to routes in the route table and the first route it matches is used no matter if a
                // better match exists. therefore if a less specific route is registered first it will catch requests that would have a better
                // match with a more specific route that was registered later.

                // ie the default route is usually the least specific route and must be registered last

                // something like a route for a cms would likely need to be the default route added last especially if you are not going to use
                // a controller segment in the route because without a controller segment the route is less specific


                // default route for folder sites must be second to last
                if (multiTenantOptions.Value.Mode == MultiTenantMode.FolderName)
                {
                    routes.MapRoute(
                        name: "folderdefault",
                        template: "{sitefolder}/{controller}/{action}/{id?}",
                        defaults: new { controller = "Home", action = "Index" },
                        constraints: new { name = new SiteFolderRouteConstraint() }
                        );
                }


                // the default route has to be added last
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }
                    );

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            })
            ;

            // https://github.com/aspnet/Announcements/issues/54
            // if you want to run the IIS pipeline for requests not handled
            // ie you won't see the IIS 404 page without this.
            // if nothing else handles the 404 then you get a blank white page in the browser
            //app.RunIISPipeline();

            //app.Run(context =>
            //{
            //    context.Response.StatusCode = 404;
            //    return Task.FromResult(0);
            //});

            DevOptions devOptions = Configuration.Get <DevOptions>("DevOptions");

            if (devOptions.DbPlatform == "ef7")
            {
                cloudscribe.Core.Repositories.EF.InitialData.InitializeDatabaseAsync(app.ApplicationServices).Wait();
                // this is using EF for the logger but using EF for Core does not mean you must use EF for logging
                // one should be able to use the MSSQL Logger while still using EF for the core repos
                // one problem with EF logging is that EF logs a lot of information stuff and if we use EF for logigng
                // then every time a log item is inserted to the db it generates more logging events
                // and thus a continuous creation of data can result so the EF logger is designed to leave out
                // EF components from logging
                // by using the mssql logger instead then no extra log items will be created and you can more easily allow
                // EF to log things of its own
                // however the mssql logger depends on the setup system which is not used by EF components
                // this dependency is more practical than technical though, you could run the db setup script for mssql logging
                // manually instead of using the setup system.
                cloudscribe.Logging.EF.DbInitializer.InitializeDatabaseAsync(app.ApplicationServices).Wait();
            }
        }
예제 #10
0
        // Configure is called after ConfigureServices is called.
        // you can change this method signature to include any dependencies that need to be injected into this method
        // you can see we added the dependency for IOptions<MultiTenantOptions>
        // so basically if you need any service in this method that was previously setup in ConfigureServices
        // you can just add it to the method signature and it will be provided by dependency injection
        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env, 
            ILoggerFactory loggerFactory,
            IOptions<MultiTenantOptions> multiTenantOptions,
            IServiceProvider serviceProvider,
            ILogRepository logRepository)
        {
            // Configure the HTTP request pipeline.

            // LogLevels
            //Debug = 1,
            //Verbose = 2,
            //Information = 3,
            //Warning = 4,
            //Error = 5,
            //Critical = 6,
            loggerFactory.MinimumLevel = LogLevel.Information;
            // Add the console logger.
            loggerFactory.AddConsole();
            // Add cloudscribe db logging
            loggerFactory.AddDbLogger(serviceProvider, logRepository);

            //app.UseCultureReplacer();

            // localization from .resx files is not really working in beta8
            // will have to wait till next release

            var localizationOptions = new RequestLocalizationOptions
            {
                // Set options here to change middleware behavior
                
                //DefaultRequestCulture = new RequestCulture(new CultureInfo("en-US")),
                SupportedCultures = new List<CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("it"),
                    new CultureInfo("fr")
                },
                SupportedUICultures = new List<CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("it"),
                    new CultureInfo("fr")
                }
                

            };



            // Optionally create an app-specific provider with just a delegate, e.g. look up user preference from DB.
            // Inserting it as position 0 ensures it has priority over any of the default providers.
            //options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
            //{

            //}));

            //app.UseRequestLocalization(localizationOptions);
            var defaultCulture = new RequestCulture(new CultureInfo("en-US"));
            //app.UseRequestLocalization(localizationOptions, defaultCulture);


            // Add the following to the request pipeline only in development environment.
            if (env.IsEnvironment("Development"))
            {
                //app.UseBrowserLink();

                app.UseDeveloperExceptionPage();
                
                //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                //app.UseErrorHandler("/Home/Error");
                //app.UseErrorPage(ErrorPageOptions.ShowAll);

                // handle 404 and other non success
                //app.UseStatusCodePages();

                // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
                // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
                // app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
                // app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
                // app.UseStatusCodePages(builder => builder.UseWelcomePage());
                //app.UseStatusCodePagesWithReExecute("/errors/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }

            // Add the platform handler to the request pipeline.
            //app.UseIISPlatformHandler();
            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            //app.UseRuntimeInfoPage("/info");

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // the only thing we are using session for is Alerts
            app.UseSession();
            //app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(20));
            

            // this is in Startup.CloudscribeCore.cs
            app.UseCloudscribeCore(multiTenantOptions,Configuration);

            // it is very important that all authentication configuration be set before configuring mvc
            // ie if app.UseFacebookAuthentication(); was below app.UseMvc the facebook login button will not be shown

            
            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                // Understanding ASP.NET Routing:

                // it is very important that routes are registered in the correct order. more specific routes must be registered first and 
                // less specific routes must be registered later. a request may match more than one route.

                // When a request comes in it is compared to routes in the route table and the first route it matches is used no matter if a 
                // better match exists. therefore if a less specific route is registered first it will catch requests that would have a better 
                // match with a more specific route that was registered later.

                // ie the default route is usually the least specific route and must be registered last

                // something like a route for a cms would likely need to be the default route added last especially if you are not going to use 
                // a controller segment in the route because without a controller segment the route is less specific


                // default route for folder sites must be second to last
                if (multiTenantOptions.Value.Mode == MultiTenantMode.FolderName)
                {
                    routes.MapRoute(
                    name: "folderdefault",
                    template: "{sitefolder}/{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" },
                    constraints: new { name = new SiteFolderRouteConstraint() }
                    );
                }


                // the default route has to be added last
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }
                    );

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            })
            ;

            // https://github.com/aspnet/Announcements/issues/54
            // if you want to run the IIS pipeline for requests not handled 
            // ie you won't see the IIS 404 page without this.
            // if nothing else handles the 404 then you get a blank white page in the browser
            //app.RunIISPipeline();

            //app.Run(context =>
            //{
            //    context.Response.StatusCode = 404;
            //    return Task.FromResult(0);
            //});



        }
예제 #11
0
        public void Configure(
            ILoggerFactory loggerFactory,
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseExceptionHandler(appBuilder =>
            {
                appBuilder.Use(async(context, next) =>
                {
                    var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;
                    if (error != null && error.Error is SecurityTokenExpiredException)
                    {
                        context.Response.StatusCode  = 401;
                        context.Response.ContentType = "application/json";
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(new
                        {
                            State = 401,
                            Msg   = "token expired"
                        }));
                    }
                    else if (error != null && error.Error != null)
                    {
                        context.Response.StatusCode  = 500;
                        context.Response.ContentType = "application/json";
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(new
                        {
                            State = 500,
                            Msg   = error.Error.Message
                        }));
                    }
                    else
                    {
                        await next();
                    }
                });
            });


            loggerFactory.AddDbLogger(serviceProvider: app.ApplicationServices, minLevel: LogLevel.Warning);

            if (!env.IsDevelopment())
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseExceptionHandler("/error/index/500");
            app.UseStatusCodePagesWithReExecute("/error/index/{0}");

            // Serve wwwroot as root
            app.UseFileServer(new FileServerOptions
            {
                // Don't expose file system
                EnableDirectoryBrowsing = false
            });

            // Adds all of the ASP.NET Core Identity related initializations at once.
            app.UseCustomIdentityServices();
            app.UseCookiePolicy();

            // app.UseNoBrowserCache();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Account}/{action=Index}/{id?}");

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


            // catch-all handler for HTML5 client routes - serve index.html
            app.Run(async context =>
            {
                context.Response.ContentType = "text/html";
                await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "index.html"));
            });
        }
 /// <summary>
 /// Adds a custom logging provider
 public static ILoggerFactory AddDbLogger(this ILoggerFactory factory, IConfiguration loggingConfiguration, ILogWriter writer)
 {
     return(factory.AddDbLogger(new LoggerSettings(loggingConfiguration), writer));
 }
예제 #13
0
        private void ConfigureLogging(ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {
            //var logRepository = serviceProvider.GetService<cloudscribe.Logging.Web.ILogRepository>();

            loggerFactory.AddConsole(minLevel: LogLevel.Warning);

            // a customizable filter for logging
            LogLevel minimumLevel = LogLevel.Warning;

            // add exclusions to remove noise in the logs
            var excludedLoggers = new List<string>
            {
                "Microsoft.Data.Entity.Storage.Internal.RelationalCommandBuilderFactory",
                "Microsoft.Data.Entity.Query.Internal.QueryCompiler",
                "Microsoft.Data.Entity.DbContext",
            };

            Func<string, LogLevel, bool> logFilter = (string loggerName, LogLevel logLevel) =>
            {
                if (logLevel < minimumLevel)
                {
                    return false;
                }

                if (excludedLoggers.Contains(loggerName))
                {
                    return false;
                }

                return true;
            };
            
            loggerFactory.AddDbLogger(serviceProvider, logFilter);
        }
예제 #14
0
        // Configure is called after ConfigureServices is called.
        // you can change this method signature to include any dependencies that need to be injected into this method
        // you can see we added the dependency for IOptions<MultiTenantOptions>
        // so basically if you need any service in this method that was previously setup in ConfigureServices
        // you can just add it to the method signature and it will be provided by dependency injection
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            IOptions <MultiTenantOptions> multiTenantOptions,
            IServiceProvider serviceProvider,
            ILogRepository logRepository)
        {
            // Configure the HTTP request pipeline.

            // LogLevels
            //Debug = 1,
            //Verbose = 2,
            //Information = 3,
            //Warning = 4,
            //Error = 5,
            //Critical = 6,
            loggerFactory.MinimumLevel = LogLevel.Information;
            // Add the console logger.
            loggerFactory.AddConsole();
            // Add cloudscribe db logging
            loggerFactory.AddDbLogger(serviceProvider, logRepository);

            //app.UseCultureReplacer();

            // localization from .resx files is not really working in beta8
            // will have to wait till next release

            var localizationOptions = new RequestLocalizationOptions
            {
                // Set options here to change middleware behavior
                DefaultRequestCulture = new RequestCulture(new CultureInfo("en-US")),
                SupportedCultures     = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("it"),
                    new CultureInfo("fr")
                },
                SupportedUICultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("it"),
                    new CultureInfo("fr")
                }
            };



            // Optionally create an app-specific provider with just a delegate, e.g. look up user preference from DB.
            // Inserting it as position 0 ensures it has priority over any of the default providers.
            //options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
            //{

            //}));

            //app.UseRequestLocalization(localizationOptions);
            app.UseRequestLocalization();


            // Add the following to the request pipeline only in development environment.
            if (env.IsEnvironment("Development"))
            {
                //app.UseBrowserLink();

                app.UseDeveloperExceptionPage();

                //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
                app.UseStatusCodePagesWithReExecute("/error/{0}");
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                //app.UseErrorHandler("/Home/Error");
                //app.UseErrorPage(ErrorPageOptions.ShowAll);

                // handle 404 and other non success
                //app.UseStatusCodePages();

                // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
                // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
                // app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
                // app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
                // app.UseStatusCodePages(builder => builder.UseWelcomePage());
                //app.UseStatusCodePagesWithReExecute("/errors/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }

            // Add the platform handler to the request pipeline.
            app.UseIISPlatformHandler();

            //app.UseRuntimeInfoPage("/info");

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // the only thing we are using session for is Alerts
            app.UseSession();
            //app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(20));


            // this is in Startup.CloudscribeCore.cs
            app.UseCloudscribeCore(multiTenantOptions, Configuration);

            // it is very important that all authentication configuration be set before configuring mvc
            // ie if app.UseFacebookAuthentication(); was below app.UseMvc the facebook login button will not be shown


            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                // Understanding ASP.NET Routing:

                // it is very important that routes are registered in the correct order. more specific routes must be registered first and
                // less specific routes must be registered later. a request may match more than one route.

                // When a request comes in it is compared to routes in the route table and the first route it matches is used no matter if a
                // better match exists. therefore if a less specific route is registered first it will catch requests that would have a better
                // match with a more specific route that was registered later.

                // ie the default route is usually the least specific route and must be registered last

                // something like a route for a cms would likely need to be the default route added last especially if you are not going to use
                // a controller segment in the route because without a controller segment the route is less specific


                // default route for folder sites must be second to last
                if (multiTenantOptions.Value.Mode == MultiTenantMode.FolderName)
                {
                    routes.MapRoute(
                        name: "folderdefault",
                        template: "{sitefolder}/{controller}/{action}/{id?}",
                        defaults: new { controller = "Home", action = "Index" },
                        constraints: new { name = new SiteFolderRouteConstraint() }
                        );
                }


                // the default route has to be added last
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }

                    );

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            })
            ;

            // https://github.com/aspnet/Announcements/issues/54
            // if you want to run the IIS pipeline for requests not handled
            // ie you won't see the IIS 404 page without this.
            // if nothing else handles the 404 then you get a blank white page in the browser
            //app.RunIISPipeline();

            //app.Run(context =>
            //{
            //    context.Response.StatusCode = 404;
            //    return Task.FromResult(0);
            //});
        }
        public void Configure(
            ILoggerFactory loggerFactory,
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            try
            {
                loggerFactory.AddLog4Net();
                loggerFactory.AddDbLogger(serviceProvider: app.ApplicationServices, scopeFactory: app.ApplicationServices.GetRequiredService <IServiceScopeFactory>(), minLevel: LogLevel.Warning);
                app.UseGlobalExceptionHandler(loggerFactory);

                app.UseAngularAntiforgeryToken();
                //app.UseExceptionHandler(appBuilder =>
                //{
                //    appBuilder.Use(async (context, next) =>
                //    {
                //        var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;
                //        if (error != null && error.Error is SecurityTokenExpiredException)
                //        {
                //            context.Response.StatusCode = 401;
                //            context.Response.ContentType = "application/json";
                //            await context.Response.WriteAsync(JsonConvert.SerializeObject(new
                //            {
                //                State = 401,
                //                Msg = "token expired"
                //            }));
                //        }
                //        else if (error != null && error.Error != null)
                //        {
                //            context.Response.StatusCode = 500;
                //            context.Response.ContentType = "application/json";
                //            await context.Response.WriteAsync(JsonConvert.SerializeObject(new
                //            {
                //                State = 500,
                //                Msg = error.Error.Message
                //            }));
                //        }
                //        else
                //        {
                //            await next();
                //        }
                //    });
                //});
                app.UseAuthentication();



                app.UseFileServer();

                app.UseResponseCompression();


                app.UseSwagger();

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/V1/swagger.json", "MSHB.ExperienceManagement API V1");
                });

                app.UseStatusCodePages();
                app.UseDefaultFiles(); // so index.html is not required
                app.UseStaticFiles();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
예제 #16
0
        // Configure is called after ConfigureServices is called.
        // you can change this method signature to include any dependencies that need to be injected into this method
        // you can see we added the dependency for IOptions<MultiTenantOptions>
        // so basically if you need any service in this method that was previously setup in ConfigureServices
        // you can just add it to the method signature and it will be provided by dependency injection
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            IOptions <MultiTenantOptions> multiTenantOptions,
            IServiceProvider serviceProvider,
            ILogRepository logRepository)
        {
            // Configure the HTTP request pipeline.

            // LogLevels
            //Debug = 1,
            //Verbose = 2,
            //Information = 3,
            //Warning = 4,
            //Error = 5,
            //Critical = 6,
            loggerFactory.MinimumLevel = LogLevel.Information;
            // Add the console logger.
            loggerFactory.AddConsole();
            // Add cloudscribe db logging
            loggerFactory.AddDbLogger(serviceProvider, logRepository);


            // Add the following to the request pipeline only in development environment.
            if (env.IsEnvironment("Development"))
            {
                //app.UseBrowserLink();

                app.UseErrorPage();

                //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
                app.UseStatusCodePagesWithReExecute("/error/{0}");
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                //app.UseErrorHandler("/Home/Error");
                //app.UseErrorPage(ErrorPageOptions.ShowAll);

                // handle 404 and other non success
                //app.UseStatusCodePages();

                // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
                // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
                // app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
                // app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
                // app.UseStatusCodePages(builder => builder.UseWelcomePage());
                //app.UseStatusCodePagesWithReExecute("/errors/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }

            //app.UseRuntimeInfoPage("/info");

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // the only thing we are using session for is Alerts
            app.UseSession();
            //app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(20));


            // this is in Startup.CloudscribeCore.cs
            app.UseCloudscribeCore(multiTenantOptions);

            // it is very important that all authentication configuration be set before configuring mvc
            // ie if app.UseFacebookAuthentication(); was below app.UseMvc the facebook login button will not be shown


            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                //if you are adding custom routes you should probably put them first
                // add your routes here


                // default route for folder sites must be second to last
                if (multiTenantOptions.Options.Mode == MultiTenantMode.FolderName)
                {
                    routes.MapRoute(
                        name: "folderdefault",
                        template: "{sitefolder}/{controller}/{action}/{id?}",
                        defaults: new { controller = "Home", action = "Index" },
                        constraints: new { name = new SiteFolderRouteConstraint() }
                        );
                }


                // the default route has to be added last
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }

                    );

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            })
            ;

            // https://github.com/aspnet/Announcements/issues/54
            // if you want to run the IIS pipeline for requests not handled
            // ie you won't see the IIS 404 page without this.
            // if nothing else handles the 404 then you get a blank white page in the browser
            //app.RunIISPipeline();

            //app.Run(context =>
            //{
            //    context.Response.StatusCode = 404;
            //    return Task.FromResult(0);
            //});
        }
예제 #17
0
        private void ConfigureLogging(
            ILoggerFactory loggerFactory, 
            IServiceProvider serviceProvider
            , cloudscribe.Logging.Web.ILogRepository logRepo
            )
        {
            
            // a customizable filter for logging
            LogLevel minimumLevel = LogLevel.Information;

            // add exclusions to remove noise in the logs
            var excludedLoggers = new List<string>
            {
                "Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware",
                "Microsoft.AspNetCore.Hosting.Internal.WebHost",
            };

            Func<string, LogLevel, bool> logFilter = (string loggerName, LogLevel logLevel) =>
            {
                if (logLevel < minimumLevel)
                {
                    return false;
                }

                if (excludedLoggers.Contains(loggerName))
                {
                    return false;
                }

                return true;
            };
            
            loggerFactory.AddDbLogger(serviceProvider, logFilter, logRepo);
        }
예제 #18
0
        // Configure is called after ConfigureServices is called.
        // you can change this method signature to include any dependencies that need to be injected into this method
        // you can see we added the dependency for IOptions<MultiTenantOptions>
        // so basically if you need any service in this method that was previously setup in ConfigureServices
        // you can just add it to the method signature and it will be provided by dependency injection
        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env, 
            ILoggerFactory loggerFactory,
            IOptions<MultiTenantOptions> multiTenantOptions,
            IServiceProvider serviceProvider,
            ILogRepository logRepository)
        {
            // Configure the HTTP request pipeline.

            //http://blog.getglimpse.com/2015/11/19/installing-glimpse-v2-beta1/
            bool enableGlimpse = Configuration.Get<bool>("DiagnosticOptions:EnableGlimpse", false);
            if(enableGlimpse)
            {
                app.UseGlimpse();
            }


            // LogLevels
            //Debug = 1,
            //Trace = 2,
            //Information = 3,
            //Warning = 4,
            //Error = 5,
            //Critical = 6,
            
            // Add the console logger.
            loggerFactory.AddConsole(minLevel: LogLevel.Warning);
            
            // a customizable filter for logging
            LogLevel minimumLevel = LogLevel.Warning;
            List<string> excludedLoggers = new List<string>();
            // add exclusions to remove noise in the logs

            // we need to filter out EF otherwise each time we persist a log item to the db more logs are generated
            // so it can become an infinite loop that keeps creating data
            // you can add any loggers that you want to exclude to reduce noise in the log
            excludedLoggers.Add("Microsoft.Data.Entity.Storage.Internal.RelationalCommandBuilderFactory");
            excludedLoggers.Add("Microsoft.Data.Entity.Query.Internal.QueryCompiler");
            excludedLoggers.Add("Microsoft.Data.Entity.DbContext");

            Func<string, LogLevel, bool> logFilter = delegate (string loggerName, LogLevel logLevel)
            {
                if (logLevel < minimumLevel) { return false; }
                if(excludedLoggers.Contains(loggerName)) { return false; }

                return true;
            };
            // Add cloudscribe db logging
            loggerFactory.AddDbLogger(serviceProvider, logRepository, logFilter);
            


            //app.UseCultureReplacer();

            // localization from .resx files is not really working in beta8
            // will have to wait till next release

            var supportedCultures = new[]
            {
                new CultureInfo("en-US"),
                new CultureInfo("it"),
                new CultureInfo("fr-FR")
            };

            var locOptions = new RequestLocalizationOptions
            {
                // You must explicitly state which cultures your application supports.
                // These are the cultures the app supports for formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures

            };
            // You can change which providers are configured to determine the culture for requests, or even add a custom
            // provider with your own logic. The providers will be asked in order to provide a culture for each request,
            // and the first to provide a non-null result that is in the configured supported cultures list will be used.
            // By default, the following built-in providers are configured:
            // - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing
            // - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie
            // - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header
            //locOptions.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
            //{
            //  // My custom request culture logic
            //  return new ProviderCultureResult("en");
            //}));
            //app.UseRequestLocalization(locOptions, 
            //    defaultRequestCulture: new RequestCulture(culture: "en-US", uiCulture: "en-US"));

            
            // Add the following to the request pipeline only in development environment.
            if (env.IsEnvironment("Development"))
            {
                //app.UseBrowserLink();

                app.UseDeveloperExceptionPage();
                
                //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }
            else
            {
                
                app.UseExceptionHandler("/Home/Error");

                // handle 404 and other non success
                //app.UseStatusCodePages();

                // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
                // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
                // app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
                // app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
                // app.UseStatusCodePages(builder => builder.UseWelcomePage());
                //app.UseStatusCodePagesWithReExecute("/errors/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }

            // Add the platform handler to the request pipeline.
            //app.UseIISPlatformHandler();
            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            //app.UseRuntimeInfoPage("/info");

            // Add static files to the request pipeline.
            app.UseStaticFiles();
            
            // the only thing we are using session for is Alerts
            app.UseSession();
            //app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(20));

            app.UseMultitenancy<SiteSettings>();

            // this is in Startup.CloudscribeCore.cs
            app.UseCloudscribeCore(multiTenantOptions,Configuration);

            // it is very important that all authentication configuration be set before configuring mvc
            // ie if app.UseFacebookAuthentication(); was below app.UseMvc the facebook login button will not be shown

            
            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                // Understanding ASP.NET Routing:

                // it is very important that routes are registered in the correct order. more specific routes must be registered first and 
                // less specific routes must be registered later. a request may match more than one route.

                // When a request comes in it is compared to routes in the route table and the first route it matches is used no matter if a 
                // better match exists. therefore if a less specific route is registered first it will catch requests that would have a better 
                // match with a more specific route that was registered later.

                // ie the default route is usually the least specific route and must be registered last

                // something like a route for a cms would likely need to be the default route added last especially if you are not going to use 
                // a controller segment in the route because without a controller segment the route is less specific


                // default route for folder sites must be second to last
                if (multiTenantOptions.Value.Mode == MultiTenantMode.FolderName)
                {
                    routes.MapRoute(
                    name: "folderdefault",
                    template: "{sitefolder}/{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" },
                    constraints: new { name = new SiteFolderRouteConstraint() }
                    );
                }


                // the default route has to be added last
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }
                    );

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            })
            ;

            // https://github.com/aspnet/Announcements/issues/54
            // if you want to run the IIS pipeline for requests not handled 
            // ie you won't see the IIS 404 page without this.
            // if nothing else handles the 404 then you get a blank white page in the browser
            //app.RunIISPipeline();

            //app.Run(context =>
            //{
            //    context.Response.StatusCode = 404;
            //    return Task.FromResult(0);
            //});

            DevOptions devOptions = Configuration.Get<DevOptions>("DevOptions");
            if (devOptions.DbPlatform == "ef7")
            {
                cloudscribe.Core.Repositories.EF.InitialData.InitializeDatabaseAsync(app.ApplicationServices).Wait();
                // this is using EF for the logger but using EF for Core does not mean you must use EF for logging
                // one should be able to use the MSSQL Logger while still using EF for the core repos
                // one problem with EF logging is that EF logs a lot of information stuff and if we use EF for logigng
                // then every time a log item is inserted to the db it generates more logging events
                // and thus a continuous creation of data can result so the EF logger is designed to leave out
                // EF components from logging
                // by using the mssql logger instead then no extra log items will be created and you can more easily allow
                // EF to log things of its own
                // however the mssql logger depends on the setup system which is not used by EF components
                // this dependency is more practical than technical though, you could run the db setup script for mssql logging
                // manually instead of using the setup system.
                cloudscribe.Logging.EF.DbInitializer.InitializeDatabaseAsync(app.ApplicationServices).Wait();
            }



        }
예제 #19
0
        // Configure is called after ConfigureServices is called.
        // you can change this method signature to include any dependencies that need to be injected into this method
        // you can see we added the dependency for IOptions<MultiTenantOptions>
        // so basically if you need any service in this method that was previously setup in ConfigureServices
        // you can just add it to the method signature and it will be provided by dependency injection
        public void Configure(
            IApplicationBuilder app, 
            IHostingEnvironment env, 
            ILoggerFactory loggerFactory,
            IOptions<MultiTenantOptions> multiTenantOptions,
            IServiceProvider serviceProvider,
            ILogRepository logRepository)
        {
            // Configure the HTTP request pipeline.

            // LogLevels
            //Debug = 1,
            //Verbose = 2,
            //Information = 3,
            //Warning = 4,
            //Error = 5,
            //Critical = 6,
            loggerFactory.MinimumLevel = LogLevel.Information;
            // Add the console logger.
            loggerFactory.AddConsole();
            // Add cloudscribe db logging
            loggerFactory.AddDbLogger(serviceProvider, logRepository);
           

            // Add the following to the request pipeline only in development environment.
            if (env.IsEnvironment("Development"))
            {
                //app.UseBrowserLink();

                app.UseErrorPage();

                //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
                app.UseStatusCodePagesWithReExecute("/error/{0}");
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                //app.UseErrorHandler("/Home/Error");
                //app.UseErrorPage(ErrorPageOptions.ShowAll);

                // handle 404 and other non success
                //app.UseStatusCodePages();

                // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
                // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
                // app.UseStatusCodePagesWithRedirects("~/errors/{0}"); // PathBase relative
                // app.UseStatusCodePagesWithRedirects("/base/errors/{0}"); // Absolute
                // app.UseStatusCodePages(builder => builder.UseWelcomePage());
                //app.UseStatusCodePagesWithReExecute("/errors/{0}");
                //app.UseStatusCodePagesWithReExecute("/error/{0}");
            }

            //app.UseRuntimeInfoPage("/info");

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // the only thing we are using session for is Alerts
            app.UseSession();
            //app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(20));
            

            // this is in Startup.CloudscribeCore.cs
            app.UseCloudscribeCore(multiTenantOptions);

            // it is very important that all authentication configuration be set before configuring mvc
            // ie if app.UseFacebookAuthentication(); was below app.UseMvc the facebook login button will not be shown

            
            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                //if you are adding custom routes you should probably put them first
                // add your routes here


                // default route for folder sites must be second to last
                if (multiTenantOptions.Options.Mode == MultiTenantMode.FolderName)
                {
                    routes.MapRoute(
                    name: "folderdefault",
                    template: "{sitefolder}/{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" },
                    constraints: new { name = new SiteFolderRouteConstraint() }
                    );
                }


                // the default route has to be added last
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }

                    );

                // Uncomment the following line to add a route for porting Web API 2 controllers.
                // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
            })
            ;

            // https://github.com/aspnet/Announcements/issues/54
            // if you want to run the IIS pipeline for requests not handled 
            // ie you won't see the IIS 404 page without this.
            // if nothing else handles the 404 then you get a blank white page in the browser
            //app.RunIISPipeline();

            //app.Run(context =>
            //{
            //    context.Response.StatusCode = 404;
            //    return Task.FromResult(0);
            //});



        }
예제 #20
0
        private static void ConfigureLogging(
            IWebHostEnvironment env,
            ILoggerFactory loggerFactory,
            IServiceProvider serviceProvider,
            IConfiguration config
            )
        {
            var      dbLoggerConfig = config.GetSection("DbLoggerConfig").Get <cloudscribe.Logging.Models.DbLoggerConfig>();
            LogLevel minimumLevel;
            string   levelConfig;

            if (env.IsProduction())
            {
                levelConfig = dbLoggerConfig.ProductionLogLevel;
            }
            else
            {
                levelConfig = dbLoggerConfig.DevLogLevel;
            }
            switch (levelConfig)
            {
            case "Debug":
                minimumLevel = LogLevel.Debug;
                break;

            case "Information":
                minimumLevel = LogLevel.Information;
                break;

            case "Trace":
                minimumLevel = LogLevel.Trace;
                break;

            default:
                minimumLevel = LogLevel.Warning;
                break;
            }

            // a customizable filter for logging
            // add exclusions in appsettings.json to remove noise in the logs
            bool logFilter(string loggerName, LogLevel logLevel)
            {
                if (dbLoggerConfig.ExcludedNamesSpaces.Any(f => loggerName.StartsWith(f)))
                {
                    return(false);
                }

                if (logLevel < minimumLevel)
                {
                    return(false);
                }

                if (dbLoggerConfig.BelowWarningExcludedNamesSpaces.Any(f => loggerName.StartsWith(f)) && logLevel < LogLevel.Warning)
                {
                    return(false);
                }
                return(true);
            }

            loggerFactory.AddDbLogger(serviceProvider, logFilter);
        }
예제 #21
0
        public void Configure(
            ILoggerFactory loggerFactory,
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            /*
             *
             * app.UseRewriter(new RewriteOptions().Add(ctx =>
             * {
             *  // checking if the hostName has www. at the beginning
             *  var req = ctx.HttpContext.Request;
             *  var hostName = req.Host;
             *  if (hostName.ToString().EndsWith("mousigha.ir"))
             *  {
             *
             *      var newHostName = hostName.ToString().Substring(0, hostName.ToString().Length - 3) + ".com";
             *      string newUrl = "";
             *
             *      newUrl = "https://" + newHostName + req.PathBase + req.Path + req.QueryString;
             *
             *
             *      var response = ctx.HttpContext.Response;
             *
             *      response.StatusCode = 301;
             *
             *
             *      response.Redirect(newUrl);
             *
             *  }
             *  if (hostName.ToString().EndsWith("mousigha.com")&& req.Scheme=="http")
             *  {
             *
             *      var newHostName = hostName;
             *      string newUrl = "";
             *
             *      newUrl = "https://" + newHostName + req.PathBase + req.Path + req.QueryString;
             *
             *
             *      var response = ctx.HttpContext.Response;
             *
             *      response.StatusCode = 301;
             *
             *
             *      response.Redirect(newUrl);
             *
             *  }
             *
             * }));
             *
             *
             */
            loggerFactory.AddDbLogger(serviceProvider: app.ApplicationServices, minLevel: LogLevel.Warning);


            if (!env.IsDevelopment())
            {
                //  app.UseHsts();
            }


            //   app.UseHttpsRedirection();

            //app.UseAntiDos();


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

            // Serve wwwroot as root


            app.UseFileServer(new FileServerOptions
            {
                // Don't expose file system
                EnableDirectoryBrowsing = false
            });


            var provider = new FileExtensionContentTypeProvider();

            provider.Mappings[".apk"] = "application/vnd.android.package-archive";

            provider.Mappings[".webmanifest"] = "application/manifest+json";


            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = provider
            });


            // Adds all of the ASP.NET Core Identity related initializations at once.
            app.UseCustomIdentityServices();
            app.UseCookiePolicy();
            app.UseRewriter(new RewriteOptions()
                            //   .AddRedirectToWww()

                            //  .AddRedirectToHttps()
                            );
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Account}/{action=Index}/{id?}");

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