過去在開發 ASP.NET 網站應用程式時,若想要使用者強制透過 HTTPS 瀏覽網站,我們會使用 IIS Rewrite Module 來進行轉址。通常會在首頁、註冊/登入、付款...等,網頁進行 Rewrite 進而確保安全性。 在 ASP.NET Core 專案中,開發人員透過現成的 Middleware ,可以更輕鬆的控制路由。本篇文章將簡單介紹如何設定自動將使用者從 HTTP 轉向 HTTPS,若有任何錯誤或建議,請各位前輩不吝指教,謝謝。 


註:本文章環境為 .NET Core 3.1






前置工作

在專案內找到 Startup.cs ,在 Configure 內加上


app.UseHttpsRedirection();



如下圖所示:





轉換不安全的連接埠 (Port)

接下來,我們要告訴程式要將不安全的 Request 轉向哪個安全的連接埠。在一般的情況下 HTTP Port 為 80 ,HTTPS Port 為 443。一般來說,我們會設定轉向 443 Port。下列有幾個轉換方式。


在開發階段,您可以在 launchsettings.json 檔案,將 URL 接調整為 HTTPS 即可,如下列範例所示:

{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "https://localhost:51842/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"api": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:51843/"
}
}
}
view raw gistfile1.txt hosted with ❤ by GitHub



測試或開發環境 (Windows Server)

1. 環境變數內設定 ASPNETCORE_HTTPS_PORT (這不適用於 reverse proxy 環境)




2. 第二個方法步驟比較多:

步驟1. 在 Program.cs 內加上 webBuilder.UseSetting("https_port", "443"); 

public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseSetting("https_port", "443");
});
}



步驟2. 在 appsetting.json 上加上 https_port": 443,

{
"https_port": 443,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}



步驟3. 在 環境變數內 加上 

Name:ASPNETCORE_HTTPS_PORT 

Value:443




額外補充:

若您的環境在 Azure App Service,可以在 組態 內 新增應程式設定 :

Name:ASPNETCORE_HTTPS_PORT 

Value:443