ASP.NET Core 2 學習筆記(五)靜態文件

以前的ASP.NET網站,只要把*.html*.css*.jpg*.png*.js等靜態文件放在項目根目錄,默認均可以直接被瀏覽;但ASP.NET Core 小改了瀏覽靜態文件的方式,默認根目錄再也不能瀏覽靜態文件,須要指定靜態文件的目錄,才能夠被瀏覽。
本篇將介紹ASP.NET Core瀏覽靜態文件的方法。css

試着在項目根目錄及wwwroot目錄中加入靜態文件,例如:html

項目根目錄\index.htmlnode

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>MyWebsite</title>
</head>
<body>
    項目根目錄的 index.html
</body>
</html>

項目根目錄\wwwroot\index.htmlgit

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>MyWebsite</title>
</head>
<body>
    wwwroot目錄的 index.html
</body>
</html>

而後在網址欄輸入:github

  • http://localhost:5000/index.html
  • http://localhost:5000/wwwroot/index.html
    會發現以上兩個連接都沒有辦法打開index.html。

瀏覽靜態文件,須要Microsoft.AspNetCore.StaticFiles中間件,ASP.NET Core 2.0以上版本默認包含。npm

啓用靜態文件

Startup.csConfigureIApplicationBuilder使用UseStaticFiles方法註冊靜態文件的Middleware:安全

Startup.cs服務器

// ...
public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseStaticFiles();

        // ...
        
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello World! \r\n");
        });
    }
}

UseStaticFiles默認啓用靜態文件的目錄是wwwroot,設定完成後再次嘗試開啓URL:app

  • http://localhost:5000/index.html
    開啓的內容會是:wwwroot目錄的index.html
  • http://localhost:5000/wwwroot/index.html
    依然沒法顯示靜態文件。

UseStaticFiles註冊的順序能夠在外層一點,比較不會通過太多沒必要要的Middleware。如圖:async

當Requset的URL文件不存在,則會轉向到Run的事件(如灰色箭頭)。

變動網站目錄

默認網站目錄是wwwroot,若是想要變動此目錄,能夠在Program.cs的WebHost Builder用UseWebRoot設置網站默認目錄。
例如:把默認網站目錄wwwroot改成public,以下:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace MyWebsite
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseWebRoot("public")
                .UseStartup<Startup>()
                .Build();
    }
}

啓用指定目錄

因爲UseStaticFiles只能拿到默認文件夾底下的文件,某些狀況會須要特定目錄也能使用靜態文件。
例如:用npm安裝的第三方庫都放在項目目錄底下的node_modules。

Startup.cs

// ...
public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions()
        {
            FileProvider = new PhysicalFileProvider(
                Path.Combine(env.ContentRootPath, @"node_modules")),
            RequestPath = new PathString("/third-party")
        });
        // ...
    }
}

以上設定就會把URL http://localhost:5000/third-party/example.js指向到項目目錄\node_modules\example.js

默認文件

比較友好的用戶體驗會但願http://localhost:5000/能夠自動指向到index.html。
能經過UseDefaultFiles設定靜態文件目錄的默認文件。

Startup.cs

// ...
public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseDefaultFiles();
        app.UseStaticFiles();
        // ...
    }
}
  • UseDefaultFiles的職責是嘗試請求默認文件。
  • UseStaticFiles 的職責是回傳請求的文件。

UseDefaultFiles必須註冊在UseStaticFiles以前。
若是先註冊UseStaticFiles,當URL是/時,UseStaticFiles找不到該文件,就會直接回傳找不到;因此就沒有機會進到UseDefaultFiles

自定義默認文件

UseDefaultFiles的默認文件以下:

  • default.htm
  • default.html
  • index.htm
  • index.html

若是默認文件的文件名不在上列清單,也能夠自定義要用什麼名稱看成默認文件。
經過DefaultFilesOptions設定後,傳入UseDefaultFiles

Startup.cs

// ...
public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        var defaultFilesOptions = new DefaultFilesOptions();
        defaultFilesOptions.DefaultFileNames.Add("custom.html");
        app.UseDefaultFiles(defaultFilesOptions);
        app.UseStaticFiles();
        // ...
    }
}

文件清單

基本上爲了網站安全性考量,不該該讓使用者瀏覽服務器上面的文件清單,但若是真有需求要讓使用者瀏覽文件清單也不是不行。

Startup.csConfigureIApplicationBuilder使用UseFileServer方法註冊文件服務器的功能:

Startup.cs

// ...
public class Startup
{
    // ...
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseFileServer(new FileServerOptions()
        {
            FileProvider = new PhysicalFileProvider(
                Path.Combine(env.ContentRootPath, @"bin")
            ),
            RequestPath = new PathString("/StaticFiles"),
            EnableDirectoryBrowsing = true
        });
    }
}

當打開http://localhost:5000/StaticFiles時,就指向到項目目錄\bin\目錄,而且能夠直接瀏覽文件目錄及文件內容,以下: 

參考

 Working with static files in ASP.NET Core

 

老司機發車啦:https://github.com/SnailDev/SnailDev.NETCore2Learning

相關文章
相關標籤/搜索