天天看點

靜态檔案

添加靜态檔案服務  

   靜态檔案通常位于 Web root(<content-root>/wwwroot)檔案夾下

    為了能夠啟用靜态檔案服務,必須配置中間件,把靜态中間件添加到管道内.靜态檔案中間件在Microsoft.AspNetCore.StaticFiles包中,調用app.UseStaticFiles();使web root(wwwroot)下檔案可以被通路

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseStaticFiles(); 
}      

 通路web root外部靜态檔案

   也可以将靜态檔案放在web root外部,但是如果想要通路web root外部靜态檔案,必須添加一個中間件到管道内

public void Confiugre(IApplicationBuilder app,IHostingEnvironment env)
{
    app.UseStaticFiles();
   //通路web root外部靜态檔案中間件
    app.UseStaticFiles(new StaticFileOptions{
         FileProvider = new  new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"img")),//實際位址
         RequestPath = new Microsoft.AspNetCore.Http.PathString("/staticFile")//通路位址
    });  
}      
靜态檔案

我們就可以使用以上位址通路 web root外部靜态檔案

靜态檔案

 允許直接浏覽目錄

   目錄浏覽允許網站使用者看到指定目錄下的目錄和檔案清單。基于安全考慮,預設情況是禁用目錄通路功能的。在Startup.Configure中調用UseDirectoryBrowser擴充方法開啟網絡應用目錄浏覽

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
       app.UseStaticFiles();
          
       app.UseDirectoryBrowser(new DirectoryBrowserOptions
       {
           FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"img")),//實際檔案目錄
           RequestPath = new Microsoft.AspNetCore.Http.PathString("/staticFile") //通路位址
       });
  }      
靜态檔案

 并且可以通過從Startup.ConfigureServices調用AddDirectory擴充方法來增加所需服務

public void ConfigureServices(IServiceCollection services)
{
    services.AddDirectoryBrowser();
}      

UseFileServer

   UseFileServer包含了UseStaticFiles,UseDefaultFiles和UseDirectoryBrowser的功能。

app.UseFileServer()      

    上面代碼啟用了靜态檔案和預設檔案,但不允許直接通路目錄

app.UseFileServer(enableDirectoryBrowsing: true);      

   上面代碼啟用了靜态檔案,預設檔案和目錄浏覽功能

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
      app.UseFileServer(new FileServerOptions
      {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"img")),
            RequestPath = new Microsoft.AspNetCore.Http.PathString("/staticFile"),
           EnableDirectoryBrowsing=true//啟用目錄浏覽 
     });
}      

  上面代碼實作了通路web root外靜态檔案

繼續閱讀