예제 #1
0
#pragma warning disable CA1822 // Member Configure does not access instance data and can be marked as static
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
#pragma warning restore CA1922
        {
            if (!env.IsDevelopment())
            {
                app.UseHsts();
            }
            app.UseHttpsRedirection()
            .UseStaticFiles()
            .UseCookiePolicy()
            .UseSession()
            .UseAuthentication()
            .UseMiddleware <Services.SessionRestore>()
            .UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "Guid parameter",
                    template: "{controller}/{action}/{guid}",
                    defaults: new { controller = "Home", action = "Index" },
                    constraints: new { guid = new GuidRouteConstraint() });
                routes.MapRoute(
                    name: "Only action",
                    template: "{controller=Home}/{action=Index}");
            });

            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    context.Response.StatusCode  = 500;
                    context.Response.ContentType = "text/html";

                    StringBuilder rsBody = new StringBuilder(2048);

                    rsBody.Append("<html lang=\"ru\"><body>\r\n")
                    .Append("Something unexpected bla-bla-bla happened... Please try refreshing the page.<br><br>\r\n");

                    var exceptionHandlerPathFeature =
                        context.Features.Get <IExceptionHandlerPathFeature>();
                    Exception unhandledExc = exceptionHandlerPathFeature.Error;
                    if (unhandledExc != null)
                    {
                        if (env.IsDevelopment())
                        {
                            rsBody.Append("</br>")
                            .Append("Unhandled exception: " + unhandledExc.ToString());
                        }

                        logger.LogError(unhandledExc, "Unhandled exception while accessing resource {0}:", context.Request.Path);
                    }

                    rsBody.Append("<a href=\"/\">Home</a><br>\r\n")
                    .Append("</body></html>\r\n");

                    await context.Response.WriteAsync(rsBody.ToString()).ConfigureAwait(false);
                });
            });
        }
예제 #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

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

            //app.UseAuthentication();

            app.UseSwagger();

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

            app.UseRouting();

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

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

            //app.UseMvc();
        }
예제 #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            //app.UseCookiePolicy(); // not in Core 3.1

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization(); //Core 3.1

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
예제 #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public static void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "DecryptRoute",
                    template: "{keyName}/{keyId}/Decrypt",
                    defaults: new { controller = "Keys", action = "Decrypt" });

                routes.MapRoute(
                    name: "GetKeyRoute",
                    template: "{keyName}",
                    defaults: new { controller = "Keys", action = "GetKey" });
            });
        }
예제 #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            app.UseHttpsRedirection();
            app.UseMvc();

            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapControllers();
            //});
        }
예제 #6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            // Using pre .Net Core 3.0 MVC routing instead of Endpoint routing (.Net core >= 3.0)
            // https://github.com/dotnet/aspnetcore/issues/9542
            // https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-core-3-0-preview-4/
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
예제 #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseDashboardSamples();


#if netcoreapp3
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
#else
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
#endif
        }
예제 #8
0
        /// <summary>
        /// Configure
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="db"></param>
        /// <param name="hangfire"></param>
        /// <param name="luceneIndexerOptions"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext db, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)
        {
            ServiceProvider = app.ApplicationServices;
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            //db.Database.Migrate();
            var dic = db.SystemSetting.ToDictionary(s => s.Name, s => s.Value); //初始化系统设置参数

            foreach (var(key, value) in dic)
            {
                CommonHelper.SystemSettings.TryAdd(key, value);
            }

            UseLuceneSearch(env, hangfire, luceneIndexerOptions);
            if (bool.Parse(Configuration["Https:Enabled"]))
            {
                app.UseHttpsRedirection().UseRewriter(new RewriteOptions().AddRedirectToNonWww()); // URL重写
            }

            app.UseSession().UseCookiePolicy();      //注入Session
            app.UseRequestIntercept();               //启用网站请求拦截
            app.UseStaticHttpContext();              //注入静态HttpContext对象
            app.UseStaticFiles(new StaticFileOptions //静态资源缓存策略
            {
                OnPrepareResponse = context =>
                {
                    context.Context.Response.Headers[HeaderNames.CacheControl] = "public,no-cache";
                    context.Context.Response.Headers[HeaderNames.Expires]      = DateTime.UtcNow.AddDays(7).ToString("R");
                },
                ContentTypeProvider = new FileExtensionContentTypeProvider(MimeMapper.MimeTypes),
            });

            app.UseHangfireServer().UseHangfireDashboard("/taskcenter", new DashboardOptions()
            {
                Authorization = new[]
                {
                    new MyRestrictiveAuthorizationFilter()
                }
            });                                                                                 //配置hangfire
            app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); //配置跨域
            app.UseResponseCaching().UseResponseCompression();                                  //启动Response缓存
            app.UseRouting();                                                                   // 放在 UseStaticFiles 之后
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();                                                        // 属性路由
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); // 默认路由
                endpoints.MapHub <MyHub>("/hubs");
            });
            HangfireJobInit.Start(); //初始化定时任务
        }
예제 #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            _serverAddressesFeature = app.ServerFeatures.Get <IServerAddressesFeature>();

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

            app.UseResponseCompression();

            app.UseStaticFiles();

            // app.UseCookiePolicy();

            app.UseResponseCaching();

            app.UseRouting();

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

            /*
             * app.Use((context, next) =>
             * {
             *  var endpointFeature = context.Features[typeof(IEndpointFeature)] as IEndpointFeature;
             *  var endpoint = endpointFeature?.Endpoint;
             *
             *  if (endpoint != null)
             *  {
             *      var metadataCollection = endpoint?.Metadata;
             *      var pattern = (endpoint as RouteEndpoint)?.RoutePattern?.RawText;
             *
             *      Console.WriteLine("Name: " + endpoint.DisplayName);
             *      Console.WriteLine($"Route Pattern: {pattern}");
             *      Console.WriteLine("Metadata Types: " + string.Join(", ", metadataCollection));
             *  }
             *  return next();
             * });
             */

            app.UseEndpoints(route =>
            {
                route.MapHub <QuotesHub>("/quotes");

                route.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{action=Index}/{id?}",
                    defaults: new { controller = "Demo", action = "Index" }
                    );
            });
        }
예제 #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                GlobalContext.SystemConfig.Debug = true;
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseDeveloperExceptionPage();
            }

            string resource = Path.Combine(env.ContentRootPath, "Resource");

            FileHelper.CreateDirectory(resource);

            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = GlobalContext.SetCacheControl
            });
            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath       = "/Resource",
                FileProvider      = new PhysicalFileProvider(resource),
                OnPrepareResponse = GlobalContext.SetCacheControl
            });

            app.UseMiddleware(typeof(GlobalExceptionMiddleware));

            app.UseCors(builder =>
            {
                builder.WithOrigins(GlobalContext.SystemConfig.AllowCorsSite.Split(',')).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
            });
            app.UseSwagger(c =>
            {
                c.RouteTemplate = "api-doc/{documentName}/swagger.json";
            });
            app.UseSwaggerUI(c =>
            {
                c.RoutePrefix = "api-doc";
                c.SwaggerEndpoint("v1/swagger.json", "TestCenter Api v1");
            });
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=ApiHome}/{action=Index}/{id?}");
            });
            GlobalContext.ServiceProvider = app.ApplicationServices;
            if (!GlobalContext.SystemConfig.Debug)
            {
                new JobCenter().Start(); // 定时任务
            }
        }
예제 #11
0
        public Startup(ILogger <Startup> logger, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            _logger = logger;
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
                          .AddEnvironmentVariables();

            if (env.IsDevelopment())
            {
                builder.AddUserSecrets <Startup>();
            }
            Configuration = builder.Build();
        }
예제 #12
0
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
 {
     applicationLifetime.ApplicationStopping.Register(OnShutdown);
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     else
     {
         // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
         app.UseHsts();
     }
     app.UseMvc();
 }
예제 #13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

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

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                // spa.Options.SourcePath = "ClientApp";
                spa.Options.SourcePath = Path.Join(env.ContentRootPath, "ClientApp");

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
예제 #14
0
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     else
     {
         app.UseHsts();
     }
     app.UseHttpsRedirection();
     app.UseStaticFiles();
     app.UseMvc();
     app.UseCors(options => options.AllowAnyOrigin());
 }
예제 #15
0
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
예제 #16
0
        public Startup(Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile($"connectionstrings{(env.IsDevelopment() ? "" : "")}.json", false, true)
                          .AddJsonFile("apisecuritysettings.json", false, true)

                          //Services

                          .AddEnvironmentVariables();

            if (env.IsEnvironment("Development"))
            {
                //Development environment settings
            }

            Configuration = builder.Build();
        }
예제 #17
0
 public Startup(IConfiguration configuration, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
 {
     if (env.IsDevelopment())
     {
         Configuration = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json", false)
                         .AddJsonFile("appsettings.Development.json", optional: true)
                         .AddJsonFile("appsettings.Local.json", optional: true)
                         .AddEnvironmentVariables()
                         .Build();
     }
     else
     {
         Configuration = configuration;
     }
 }
예제 #18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            app.UseCors("AllowAllOrigin");

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

            app.UseIdentityServer();

            //app.UseMvc();
        }
예제 #19
0
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     app.UseRouting();
     app.UseEndpoints(routes =>
     {
         routes.MapHub <ControlHub>("/ControlHub");
     });
     app.Run(async(context) =>
     {
         MazeGenerator mazeGenerator = new MazeGenerator();
         Maze maze = mazeGenerator.GenerateMaze();
         await context.Response.WriteAsync(JsonSerializer.Serialize(maze.GetMazeDTO()));
     });
 }
예제 #20
0
파일: Startup.cs 프로젝트: liyojose/Match
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env, Seed seeder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(builder => {
                    builder.Run(async context => {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                        var error = context.Features.Get <IExceptionHandlerFeature>();
                        if (error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
            }

            seeder.SeedUsers();
            app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            app.UseAuthentication();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseRouting();

            //app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            //app.UseMvc(routes =>
            //{
            //    routes.MapSpaFallbackRoute(
            //        name: "spa-fallback",
            //        defaults: new { controller = "FallbackController", action = "Index" }
            //    );
            //});
        }
예제 #21
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                // app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

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

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

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

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Portfolio}/{action=Index}/{id?}");
            });
        }
예제 #22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(new GlobalExceptionHandler(loggerFactory).Action);
            }

            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "DPC Notification API");
            });

            app.UseMvcWithDefaultRoute();
        }
예제 #23
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            //test
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSession();//this must be above app.UseMVC
            //app.UseMvcWithDefaultRoute();
            app.UseStaticFiles();
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "Default",
                    pattern: "{controller=Home}/{action=Index}/{id?}"
                    );
            });

            app.UseStatusCodePagesWithReExecute("/error/{0}");
        }
예제 #24
0
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env, IApiVersionDescriptionProvider provider)
        {
            if (env.IsDevelopment())
            {
                app.UseCors("Development");
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseCors("Production"); // Usar apenas nas demos => Configuração Ideal: Production
                app.UseHsts();
            }

            app.UseAuthentication();

            app.UseMiddleware <ExceptionMiddleware>();

            app.UseMvcConfiguration();

            app.UseSwaggerConfig(provider);

            app.UseLoggingConfiguration();
        }
예제 #25
0
파일: Startup.cs 프로젝트: mccj/FileManager
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseNSwagSwaggerUI();
            app.UseHealthChecks("/health");
            app.UseFileManagerUI("/Browser", f => f
                                 //.UseDefaultFileManagerUI()
                                 .UseFileExplorerUI()
                                 );

#if netcoreapp3
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
#else
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
#endif
        }
예제 #26
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
        {
            bool useSsl      = StartupHelpers.GetLogicalSetting("useSsl", Configuration);
            bool showUrls    = StartupHelpers.GetLogicalSetting("ShowUrls", Configuration);
            bool openBrowser = StartupHelpers.GetLogicalSetting("OpenBrowser", Configuration);

            string defaultFiles = Configuration["DefaultFiles"];

            if (string.IsNullOrEmpty(defaultFiles))
            {
                defaultFiles = "index.html,default.htm,default.html";
            }

            var strPort = Configuration["Port"];

            if (!int.TryParse(strPort, out Port))
            {
                Port = 5000;
            }

            if (UseLiveReload)
            {
                app.UseLiveReload();
            }

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

            if (showUrls)
            {
                app.Use(async(context, next) =>
                {
                    var url =
                        $"{context.Request.Method}  {context.Request.Scheme}://{context.Request.Host}  {context.Request.Path}{context.Request.QueryString}";
                    Console.WriteLine(url);
                    await next();
                });
            }

            app.UseDefaultFiles(new DefaultFilesOptions
            {
                FileProvider     = new PhysicalFileProvider(WebRoot),
                DefaultFileNames = new List <string>(defaultFiles.Split(',', ';'))
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(WebRoot),
                RequestPath  = new PathString("")
            });

#if USE_RAZORPAGES
            if (UseRazor)
            {
                app.UseRouting();
                app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
            }
#endif
            var url        = $"http{(useSsl ? "s" : "")}://localhost:{Port}";
            var extensions = Configuration["Extensions"];

            string headerLine = new string('-', Program.AppHeader.Length);
            Console.WriteLine(headerLine);
            Console.WriteLine(Program.AppHeader);
            Console.WriteLine(headerLine);
            Console.WriteLine($"(c) West Wind Technologies, 2018-{DateTime.Now.Year}\r\n");
            Console.Write($"Site Url     : ");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(url);
            Console.ResetColor();
            Console.WriteLine($"Web Root     : {WebRoot}");
            Console.WriteLine(
                $"Extensions   : {(string.IsNullOrEmpty(extensions) ? $"{(UseRazor ? ".cshtml," : "")},.css,.js,.htm,.html,.ts" : extensions)}");
            Console.WriteLine($"Live Reload  : {UseLiveReload}");

#if USE_RAZORPAGES
            Console.WriteLine($"Use Razor    : {UseRazor}");
#endif
            Console.WriteLine($"Show Urls    : {showUrls}");
            Console.WriteLine($"Open Browser : {openBrowser}");
            Console.WriteLine($"Default Pages: {defaultFiles}");

            Console.WriteLine();
            Console.WriteLine("'LiveReloadServer --help' for start options...");
            Console.WriteLine();
            Console.WriteLine("Ctrl-C or Ctrl-Break to exit...");

            Console.WriteLine("----------------------------------------------");

            var oldColor = Console.ForegroundColor;
            foreach (var assmbly in LoadedPrivateAssemblies)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Additional Assembly: " + assmbly);
            }
            foreach (var assmbly in FailedPrivateAssemblies)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Failed Additional Assembly: " + assmbly);
            }
            Console.ForegroundColor = oldColor;

            if (openBrowser)
            {
                StartupHelpers.OpenUrl(url);
            }
        }