/// <summary>
        /// Creates a new instance of the SendFileMiddleware.
        /// </summary>
        /// <param name="next">The next middleware in the pipeline.</param>
        /// <param name="options">The configuration for this middleware.</param>
        public DirectoryBrowserMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, DirectoryBrowserOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (hostingEnv == null)
            {
                throw new ArgumentNullException(nameof(hostingEnv));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (options.Formatter == null)
            {
                throw new ArgumentException(Resources.Args_NoFormatter);
            }
            options.ResolveFileProvider(hostingEnv);

            _next = next;
            _options = options;
            _matchUrl = options.RequestPath;
        }
Esempio n. 2
0
        public static void Main()
        {
            var path         = Path.Combine(Directory.GetCurrentDirectory(), "doc");
            var fileProvider = new PhysicalFileProvider(path);
            var fileOptions  = new StaticFileOptions
            {
                FileProvider = fileProvider,
                RequestPath  = "/documents"
            };
            var diretoryOptions = new DirectoryBrowserOptions
            {
                FileProvider = fileProvider,
                RequestPath  = "/documents"
            };
            var defaultOptions1 = new DefaultFilesOptions();
            var defaultOptions2 = new DefaultFilesOptions
            {
                RequestPath  = "/documents",
                FileProvider = fileProvider,
            };

            defaultOptions1.DefaultFileNames.Add("readme.html");
            defaultOptions2.DefaultFileNames.Add("readme.html");

            Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(builder => builder.Configure(app => app
                                                                   .UseDefaultFiles(defaultOptions1)
                                                                   .UseDefaultFiles(defaultOptions2)
                                                                   .UseStaticFiles()
                                                                   .UseStaticFiles(fileOptions)
                                                                   .UseDirectoryBrowser()
                                                                   .UseDirectoryBrowser(diretoryOptions)))
            .Build()
            .Run();
        }
Esempio n. 3
0
        public static void UseStaticFilesAndDirectoryBrowser(this IApplicationBuilder app)
        {
            var path         = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/files");
            var fileProvider = new PhysicalFileProvider(path);

            // add file extention mapping
            var contenTypeProvider = new FileExtensionContentTypeProvider();

            contenTypeProvider.Mappings.Add(".7z", "application/x-7z-compressed");

            var fileOptions = new StaticFileOptions
            {
                ContentTypeProvider = contenTypeProvider,
                FileProvider        = fileProvider,
                RequestPath         = "/files"
            };

            var directoryOptions = new DirectoryBrowserOptions
            {
                FileProvider = fileProvider,
                RequestPath  = "/files"
            };

            app.UseStaticFiles(fileOptions)
            .UseDirectoryBrowser(directoryOptions);
        }
        /// <summary>
        /// Creates a new instance of the SendFileMiddleware.
        /// </summary>
        /// <param name="next">The next middleware in the pipeline.</param>
        /// <param name="hostingEnv">The <see cref="IHostingEnvironment"/> used by this middleware.</param>
        /// <param name="encoder">The <see cref="HtmlEncoder"/> used by the default <see cref="HtmlDirectoryFormatter"/>.</param>
        /// <param name="options">The configuration for this middleware.</param>
        public DirectoryBrowserMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, HtmlEncoder encoder, IOptions <DirectoryBrowserOptions> options)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (hostingEnv == null)
            {
                throw new ArgumentNullException(nameof(hostingEnv));
            }

            if (encoder == null)
            {
                throw new ArgumentNullException(nameof(encoder));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _next         = next;
            _options      = options.Value;
            _fileProvider = _options.FileProvider ?? Helpers.ResolveFileProvider(hostingEnv);
            _formatter    = options.Value.Formatter ?? new HtmlDirectoryFormatter(encoder);
            _matchUrl     = _options.RequestPath;
        }
Esempio n. 5
0
        public static DirectoryBrowserOptions GetDirectoryBrowserOptions(IDictionary <string, string> properties)
        {
            if (properties == null)
            {
                return(null);
            }

            var path = properties.GetNullifiedValue("DirectoryBrowserRequestPath");

            if (string.IsNullOrWhiteSpace(path))
            {
                return(null);
            }

            var rootPath = properties.GetNullifiedValue(nameof(RootPath));

            if (string.IsNullOrWhiteSpace(rootPath))
            {
                return(null);
            }

            var options = new DirectoryBrowserOptions();

            options.RequestPath = path;
            try
            {
                options.FileProvider = new PhysicalFileProvider(rootPath);
            }
            catch (Exception e)
            {
                throw new DavServerException("0005: There is a configuration error, please check the appsettings.json file.", e);
            }
            return(options);
        }
Esempio n. 6
0
 /// <summary>
 /// Creates a combined options class for all of the static file middleware components.
 /// </summary>
 public FileServerOptions()
     : base(new SharedOptions())
 {
     StaticFileOptions       = new StaticFileOptions(SharedOptions);
     DirectoryBrowserOptions = new DirectoryBrowserOptions(SharedOptions);
     DefaultFilesOptions     = new DefaultFilesOptions(SharedOptions);
     EnableDefaultFiles      = true;
 }
        /// <summary>
        /// Enable directory browsing with the given options
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IAppBuilder UseDirectoryBrowser(this IAppBuilder builder, DirectoryBrowserOptions options)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            return builder.Use(typeof(DirectoryBrowserMiddleware), options);
        }
Esempio n. 8
0
        /// <summary>
        /// Enable directory browsing with the given options
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IAppBuilder UseDirectoryBrowser(this IAppBuilder builder, DirectoryBrowserOptions options)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            return(builder.Use <DirectoryBrowserMiddleware>(options));
        }
        /// <summary>
        /// Enable directory browsing with the given options
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IBuilder UseDirectoryBrowser(this IBuilder builder, DirectoryBrowserOptions options)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            return builder.Use(next => new DirectoryBrowserMiddleware(next, options).Invoke);
        }
Esempio n. 10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors("XiaoQiAllowOrigins");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.RoutePrefix = string.Empty;
            });
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\", Configuration.GetValue <string>("StoredFilesPath"));

            FileHelper.CheckDirExist(filePath);
            var dir = new DirectoryBrowserOptions();

            dir.FileProvider = new PhysicalFileProvider(filePath);
            app.UseDirectoryBrowser(dir);

            var staticFile = new StaticFileOptions();

            staticFile.FileProvider = new PhysicalFileProvider(filePath);
            //手动设置MIME Type,或者设置一个默认值, 以解决某些文件MIME Type文件识别不到,出现404错误
            staticFile.ServeUnknownFileTypes = true;
            staticFile.DefaultContentType    = "text/plain;charset=utf-8"; //设置默认MIME Type
            var provider = new FileExtensionContentTypeProvider();         //使用一组默认映射创建新的提供程序

            provider.Mappings[".txt"] = "text/plain;charset=utf-8";        //手动设置对应MIME Type
            provider.Mappings.Add(".log", "text/plain");                   //手动设置对应MIME Type
            staticFile.ContentTypeProvider = provider;                     //将文件映射到内容类型

            app.UseStaticFiles(staticFile);
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    DefaultContentType = "text/plain;charset=utf-8"//设置默认MIME Type
            //});


            app.UseRouting();

            //认证
            app.UseAuthentication();
            //授权
            app.UseAuthorization();



            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
        /// <summary>
        /// Enable directory browsing with the given options
        /// </summary>
        /// <param name="app"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseDirectoryBrowser(this IApplicationBuilder app, DirectoryBrowserOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return app.UseMiddleware<DirectoryBrowserMiddleware>(options);
        }
Esempio n. 12
0
        public static void Main()
        {
            var options = new DirectoryBrowserOptions
            {
                Formatter = new ListDirectoryFormatter()
            };

            Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(builder => builder.Configure(
                                          app => app.UseDirectoryBrowser(options)))
            .Build()
            .Run();
        }
Esempio n. 13
0
        public void Configuration(IAppBuilder builder)
        {
            // Configure SignalR DI
            var resolver = new DefaultDependencyResolver();

            resolver.Register(typeof(Chat), () => new Chat(_documentStore));
            var hubConfig = new HubConfiguration
            {
                Resolver = resolver
            };

            // Nancy DI container is configured in its bootstrapper
            var sampleBootstrapper = new SampleBootstrapper(_documentStore);

            // Note: it's perfectly viable to have an over-arching single application container
            // and configure signalr and nancy to use it.


            builder
            .Map("/fault",
                 faultBuilder => faultBuilder
                 .UseErrorPage(new ErrorPageOptions {
                ShowExceptionDetails = true
            })
                 .Use((context, next) => { throw new Exception("oops!"); }))
            .Map("/files",
                 siteBuilder =>
            {
                siteBuilder.UseBasicAuthentication("nancy-signalr", (id, secret) =>
                {
                    IEnumerable <Claim> claims = new[] { new Claim("id", id) };
                    return(Task.FromResult(claims));
                });

                var options = new DirectoryBrowserOptions
                {
                    FileSystem = new PhysicalFileSystem(@"c:\")
                };
                // .UseDenyAnonymous()
                siteBuilder.UseDirectoryBrowser(options);
            })
            .UseFileServer(new FileServerOptions
            {
                RequestPath = new PathString("/scripts"),
                FileSystem  = new PhysicalFileSystem("scripts")
            })
            .Map("/site", siteBuilder => siteBuilder.UseNancy(cfg => cfg.Bootstrapper = sampleBootstrapper))
            .MapHubs(hubConfig)
            .UseWelcomePage();
        }
Esempio n. 14
0
        public DirectoryBrowserMiddleware(AppFunc next, DirectoryBrowserOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _options = options;
            _matchUrl = options.RequestPath + "/";
            _next = next;
        }
        /// <summary>
        /// Enable directory browsing with the given options
        /// </summary>
        /// <param name="app"></param>
        /// <param name="configureOptions"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseDirectoryBrowser(this IApplicationBuilder app, Action<DirectoryBrowserOptions> configureOptions)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (configureOptions == null)
            {
                throw new ArgumentNullException(nameof(configureOptions));
            }

            var options = new DirectoryBrowserOptions();
            configureOptions(options);

            return app.UseMiddleware<DirectoryBrowserMiddleware>(options);
        }
Esempio n. 16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors("AllowAll");
            app.UseFileServer();
            app.UseSignalR(routes =>
            {
                routes.MapHub <MessageHub>("/MessageHub");
            });


            var dir = new DirectoryBrowserOptions();

            dir.FileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
            app.UseDirectoryBrowser(dir);
            var staticfile = new StaticFileOptions();

            staticfile.FileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory);
            app.UseStaticFiles(staticfile);
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

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

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
Esempio n. 17
0
        public static void Run()
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "content");

            var options = new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(path),
                RequestPath  = "/aaa"
            };

            var directoryBrowserOptions = new DirectoryBrowserOptions()
            {
                FileProvider = new PhysicalFileProvider(path),
                RequestPath  = "/aaa"
            };


            var defaultFileOptions = new DefaultFilesOptions()
            {
                FileProvider = new PhysicalFileProvider(path),
                RequestPath  = "/aaa"
            };

            defaultFileOptions.DefaultFileNames.Add("readme.html");

            var host = Host.CreateDefaultBuilder()
                       .ConfigureWebHostDefaults(builder =>
            {
                builder.Configure(app =>
                {
                    app.UseDefaultFiles();
                    app.UseDefaultFiles(defaultFileOptions);
                    app.UseStaticFiles();
                    app.UseStaticFiles(options);
                    app.UseDirectoryBrowser();
                    app.UseDirectoryBrowser(directoryBrowserOptions);
                });
            })
                       .Build();

            host.Run();
        }
Esempio n. 18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var dir = new DirectoryBrowserOptions();

            dir.FileProvider = new PhysicalFileProvider("/log/");
            app.UseDirectoryBrowser(dir);
            var staticfile = new StaticFileOptions();

            staticfile.FileProvider          = new PhysicalFileProvider("/log/"); //指定目录 这里指定C盘,也可以是其它目录
            staticfile.ServeUnknownFileTypes = true;
            staticfile.DefaultContentType    = "application/x-msdownload";        //设置默认  MIME

            var provider = new FileExtensionContentTypeProvider();

            provider.Mappings.Add(".log", "text/plain");//手动设置对应MIME
            staticfile.ContentTypeProvider = provider;
            app.UseStaticFiles(staticfile);
        }
        /// <summary>
        /// Creates a new instance of the SendFileMiddleware.
        /// </summary>
        /// <param name="next">The next middleware in the pipeline.</param>
        /// <param name="options">The configuration for this middleware.</param>
        public DirectoryBrowserMiddleware(AppFunc next, DirectoryBrowserOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (options.Formatter == null)
            {
                throw new ArgumentException(Resources.Args_NoFormatter);
            }
            if (options.FileSystem == null)
            {
                options.FileSystem = new PhysicalFileSystem("." + options.RequestPath.Value);
            }

            _next = next;
            _options = options;
            _matchUrl = options.RequestPath;
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            var path         = Path.Combine(Directory.GetCurrentDirectory(), "doc");
            var fileProvider = new PhysicalFileProvider(path);
            var options      = new StaticFileOptions
            {
                FileProvider = fileProvider,
                RequestPath  = "/document"
            };

            var direcotryOptions = new DirectoryBrowserOptions
            {
                FileProvider = fileProvider,
                RequestPath  = "/document"
            };

            Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(builder => builder.Configure(app => app.UseStaticFiles()
                                                                   .UseStaticFiles(options)
                                                                   .UseDirectoryBrowser()
                                                                   .UseDirectoryBrowser(direcotryOptions)))
            .Build()
            .Run();
        }
 public static void JTUseDirectoryBrowser(this IApplicationBuilder app, DirectoryBrowserOptions options)
 {
     app.UseDirectoryBrowser(options);
 }
Esempio n. 22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //添加文件日志
            loggerFactory.AddFile(Configuration.GetSection("FileLogging"));

            //配置FluentValidation的本地化
            app.ConfigLocalizationFluentValidation();

            //注册管道是有顺序的

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

            //检查到相应配置启用https跳转
            if (Configuration.GetValue("UseHttpsRedirection", false) &&
                (Configuration.GetSection("RafHost").GetSection("Endpoints").GetSection("Https")
                 .GetValue("IsEnabled", false) || Environment.IsDevelopment()))
            {
                //app.UseHsts();
                HstsBuilderExtensions.UseHsts(app);
                //注册强制Https跳转到管道
                app.UseHttpsRedirection();
            }

            //注册响应压缩到管道
            app.UseResponseCompression();

            //注册内容安全策略到管道
            // Content Security Policy
            app.UseCsp(csp =>
            {
                // If nothing is mentioned for a resource class, allow from this domain
                csp.ByDefaultAllow
                .FromSelf();

                // Allow JavaScript from:
                csp.AllowScripts
                .FromSelf()     //This domain
                .AllowUnsafeInline()
                .AllowUnsafeEval()
                .From("localhost:5000")     //These two domains
                .From("localhost:5001")
                .From("localhost:5002")
                .From("localhost:5003")
                .From("localhost:5004")
                .From("localhost:5005")
                .From("ajax.aspnetcdn.com")
                .From("cdnjs.cloudflare.com");
                //.AddNonce();//此项与AllowUnsafeInline冲突,会被AllowUnsafeInline选项覆盖

                // CSS allowed from:
                csp.AllowStyles
                .FromSelf()
                .AllowUnsafeInline()
                .From("localhost:5000")     //These two domains
                .From("localhost:5001")
                .From("localhost:5002")
                .From("localhost:5003")
                .From("localhost:5004")
                .From("localhost:5005")
                .From("ajax.aspnetcdn.com")
                .From("fonts.googleapis.com")
                .From("cdnjs.cloudflare.com");
                //.AddNonce();//此项与AllowUnsafeInline冲突,会被AllowUnsafeInline选项覆盖

                csp.AllowImages
                .FromSelf()
                .DataScheme()
                .From("localhost:5000")     //These two domains
                .From("localhost:5001")
                .From("localhost:5002")
                .From("localhost:5003")
                .From("localhost:5004")
                .From("localhost:5005")
                .From("ajax.aspnetcdn.com");

                // HTML5 audio and video elemented sources can be from:
                csp.AllowAudioAndVideo
                .FromNowhere();    //Nowhere, no media allowed

                // Contained iframes can be sourced from:
                csp.AllowFrames
                .FromSelf();

                // Allow AJAX, WebSocket and EventSource connections to:
                csp.AllowConnections
                .ToSelf()
                .To("ws://localhost:5000")
                .To("wss://localhost:5001")
                ;

                // Allow fonts to be downloaded from:
                csp.AllowFonts
                .FromSelf()
                .From("fonts.gstatic.com")
                .From("ajax.aspnetcdn.com");

                // Allow object, embed, and applet sources from:
                csp.AllowPlugins
                .FromNowhere();

                // Allow other sites to put this in an iframe?
                csp.AllowFraming
                .FromAnywhere();     // Block framing on other sites, equivalent to X-Frame-Options: DENY

                if (env.IsDevelopment())
                {
                    // Do not block violations, only report
                    // This is a good idea while testing your CSP
                    // Remove it when you know everything will work
                    //csp.SetReportOnly();
                    // Where should the violation reports be sent to?
                    //csp.ReportViolationsTo("/csp-report");
                }

                // Do not include the CSP header for requests to the /api endpoints
                //csp.OnSendingHeader = context =>
                //{
                //    context.ShouldNotSend = context.HttpContext.Request.Path.StartsWithSegments("/api");
                //    return Task.CompletedTask;
                //};
            });

            //注册请求本地化到管道
            var locOptions = app.ApplicationServices.GetService <IOptions <RequestLocalizationOptions> >();

            app.UseRequestLocalization(locOptions.Value);

            //注册默认404页面到管道
            app.UseStatusCodePages(async context =>
            {
                if (context.HttpContext.Response.StatusCode != (int)HttpStatusCode.NotFound)
                {
                    return;
                }

                PathString pathString           = "/Home/NotFound";
                QueryString queryString         = new QueryString();
                PathString originalPath         = context.HttpContext.Request.Path;
                QueryString originalQueryString = context.HttpContext.Request.QueryString;
                context.HttpContext.Features.Set <IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature()
                {
                    OriginalPathBase    = context.HttpContext.Request.PathBase.Value,
                    OriginalPath        = originalPath.Value,
                    OriginalQueryString = (originalQueryString.HasValue ? originalQueryString.Value : null)
                });
                context.HttpContext.Request.Path        = pathString;
                context.HttpContext.Request.QueryString = queryString;
                try
                {
                    await context.Next(context.HttpContext);
                }
                finally
                {
                    context.HttpContext.Request.QueryString = originalQueryString;
                    context.HttpContext.Request.Path        = originalPath;
                    context.HttpContext.Features.Set <IStatusCodeReExecuteFeature>(null);
                }
            });

            //注册开发环境文件浏览器
            if (Environment.IsDevelopment())
            {
                var dir = new DirectoryBrowserOptions();
                dir.FileProvider = new PhysicalFileProvider(Environment.ContentRootPath);
                dir.RequestPath  = "/dir";
                app.UseDirectoryBrowser(dir);

                var contentTypeProvider = new FileExtensionContentTypeProvider();
                contentTypeProvider.Mappings.Add(".log", "text/plain");

                var devStaticFileOptions = new StaticFileOptions
                {
                    FileProvider          = new PhysicalFileProvider(Environment.ContentRootPath),
                    RequestPath           = "/dir",
                    ServeUnknownFileTypes = true,
                    DefaultContentType    = "application/octet-stream",
                    ContentTypeProvider   = contentTypeProvider
                };

                app.UseStaticFiles(devStaticFileOptions);
            }

            //注册开发环境的npm和bower资源
            if (Environment.IsDevelopment())
            {
                var npmContentTypeProvider = new FileExtensionContentTypeProvider();
                var npmStaticFileOptions   = new StaticFileOptions
                {
                    FileProvider          = new PhysicalFileProvider(Environment.ContentRootPath + "/node_modules"),
                    RequestPath           = "/npm",
                    ServeUnknownFileTypes = false,
                    ContentTypeProvider   = npmContentTypeProvider
                };

                app.UseStaticFiles(npmStaticFileOptions);

                var bowerContentTypeProvider = new FileExtensionContentTypeProvider();
                var bowerStaticFileOptions   = new StaticFileOptions
                {
                    FileProvider          = new PhysicalFileProvider(Environment.ContentRootPath + "/bower_components"),
                    RequestPath           = "/bower",
                    ServeUnknownFileTypes = false,
                    ContentTypeProvider   = bowerContentTypeProvider
                };

                app.UseStaticFiles(bowerStaticFileOptions);
            }

            //注册静态文件到管道(wwwroot文件夹)
            app.UseStaticFiles();

            //注册Cookie策略到管道(GDPR)
            app.UseCookiePolicy();

            //注册跨域策略到管道
            app.UseCors("CorsPolicy");

            //注册IdentityServer4到管道
            app.UseIdentityServer();

            //注册SignalR到管道
            app.UseSignalR(routes =>
            {
                routes.MapHub <ChatHub>("/chatHub");
            });

            //注册MVC到管道
            app.UseMvc(routes =>
            {
                routes
                .MapRoute(
                    name: "area",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                    )
                .MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Esempio n. 23
0
        /// <summary>
        /// Enable directory browsing with the given options
        /// </summary>
        /// <param name="app"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseDirectoryBrowser(this IApplicationBuilder app, DirectoryBrowserOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(app.UseMiddleware <DirectoryBrowserMiddleware>(Options.Create(options)));
        }
Esempio n. 24
0
 /// <summary>
 /// Enable directory browsing with the given options
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static IApplicationBuilder UseDirectoryBrowser([NotNull] this IApplicationBuilder builder, [NotNull] DirectoryBrowserOptions options)
 {
     return(builder.UseMiddleware <DirectoryBrowserMiddleware>(options));
 }
Esempio n. 25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // Environment Check.
            if (env.IsProduction())
            {
                //app.UseHsts();
                app.UseExceptionHandler("/error");
            }
            else
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else if (env.IsEnvironment("Test"))
                {
                    app.Run(async(context) =>
                    {
                        await context.Response.WriteAsync("Test Environment is not yet supported.");
                    });
                }
                else
                {
                    app.Run(async(context) =>
                    {
                        await context.Response.WriteAsync("Unknown Environment.");
                    });
                }
            }
            //app.UseHttpsRedirection();

            //app.Map("/system", SystemHandler);
            app.Map("/error", ap => ap.Run(async context =>
            {
                await context.Response.WriteAsync("Error");
            }));

            app.Use(async(context, next) =>
            {
                // Do Something...
                await next.Invoke();
            });

            // Status Codes (Errors).
            //app.UseMiddleware<ErrorHandlingMiddleware>();
            app.UseStatusCodePages();
            //app.UseStatusCodePages("text/plain", "Error. Status code : {0}");
            //app.UseStatusCodePagesWithRedirects("/error?code={0}");
            //app.UseStatusCodePagesWithReExecute("/error", "?code={0}");

            //app.UseMiddleware<TokenMiddleware>();
            app.UseToken("CS");

            app.UseRouting();

            // Default Files.
            DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();

            defaultFilesOptions.DefaultFileNames.Add("default.xhtml");
            defaultFilesOptions.DefaultFileNames.Add("index.xhtml");
            app.UseDefaultFiles();

            // Directory Browser.
            string pathToPublicFolder = Path.Combine(Directory.GetCurrentDirectory(), "Content", "public");
            string publicFolderAlias  = "/files";
            DirectoryBrowserOptions directoryBrowserOptions = new DirectoryBrowserOptions()
            {
                FileProvider = new PhysicalFileProvider(pathToPublicFolder),
                RequestPath  = new PathString(publicFolderAlias)
            };

            app.UseDirectoryBrowser(directoryBrowserOptions);

            // Static Files.
            app.UseStaticFiles();             // [/] -> [/www].
            StaticFileOptions staticFileOptions = new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(pathToPublicFolder),
                RequestPath  = new PathString(publicFolderAlias)
            };

            app.UseStaticFiles(staticFileOptions);             // [/files] -> [/public].

            //app.UseFileServer(enableDirectoryBrowsing: true);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    int x = 0;
                    x     = x / x;                 // => Exception.
                    await context.Response.WriteAsync($"Hello World! Running at {environment.ContentRootPath}.");
                });
            });

            /*
             * app.Run(async (context) =>
             * {
             *      await context.Response.WriteAsync("End of the Line!");
             * });
             */
        }