今天來說一個很簡單但是花了我一點時間找的東西,在 .Net 6 中 我要改變我的首頁,你開專案的時候預設會去 /Index
在專案中 Pages/IndexModel ,但是我想要改變我的首頁該如何處理,這有分成靜態檔案(在 wwwroot 裡面的),跟非靜態檔案的作法
方法1. 最簡單的偷懶法,直接寫在 IndeModel 的 OnGet 直接 Redirect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class IndexModel : PageModel | |
{ | |
private readonly ILogger<IndexModel> _logger; | |
public IndexModel(ILogger<IndexModel> logger) | |
{ | |
_logger = logger; | |
} | |
public void OnGet() | |
{ | |
Response.Redirect("/NewIndex"); | |
//Response.Redirect("/index.html"); | |
} | |
} | |
但是這會用到 302 跳轉
不過這招很簡單,而且你也可以直接跳轉到靜態的地方像是 原本你放在 /wwwroot/index.html
方法2. 修改 Program.cs,使用 app.Use
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.Use(async (context, next) => | |
{ | |
if (context.Request.Path == "/") | |
{ | |
context.Request.Path = "/NewIndex"; | |
//work | |
//context.Request.Path = "/index.html"; | |
} | |
await next.Invoke(); | |
}); | |
app.UseHttpsRedirection(); | |
這作法好處就是不會出現跳轉,直接會到 /NewIndex ,這方法對 靜態檔案也是一樣有效
方法3. 只能用於靜態檔案,也就是 /wwwroot 下面的檔案
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.UseDefaultFiles(new DefaultFilesOptions | |
{ | |
DefaultFileNames = new List<string> {"not_existed_test.html" ,"index.html" } | |
}); | |
app.UseStaticFiles(); | |
如果這些靜態檔案都找不到得情況下,則就會去啟動 /Index
看起來不難,但是因為作法很多,有些不是達到我預期效果,這邊就筆記一下