2020年4月10日 星期五

設定 ASP.NET Core 3.x 的起始連結(URL)位址

ASP.NET Core 3.x 本身提供了多種設定起始連結的方式,和過去 2.x 版本其實相差不大,因此下面的範例應該也都適用於 2.x 版本。


ASP.NET Core 應用程式預設是使用以下兩個位址做為起始連結

  • http://localhost:5000
  • https://localhost:5001

以下將介紹幾種修改起始連結的方式

1. 使用 UseUrls()

直接將連結寫死在程式碼裡,通常實際的專案不會這樣寫(你硬要也不是不行),方式為在 Program.cs 裡的CreateHostBuilder方法內加上一行程式碼如下

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.UseUrls("http://localhost:5003", "https://localhost:5004");  // 加上此行程式碼
         });
}


2. 使用環境變數

採用添加系統環境變數的方式來指定起始連結,如下

使用命令提示字元(Command Prompt):

setx ASPNETCORE_URLS "http://localhost:5003;https://localhost:5004"

使用 Powershell:

$Env: ASPNETCORE_URLS = "http://localhost:5003;https://localhost:5004"

使用 Bash:

export ASPNETCORE_URLS="http://localhost:5003;https://localhost:5004"

若是在 Visual Studio Code 開發環境下,也可對專案 .vscode 目錄下的 launch.json 新增一行執行時帶上的環境變數,請看以下範例

{

   "version": "0.2.0",
   "configurations": [
        {
            "name": ".NET Core Launch (web)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",            

            /*** 省略部分代碼 ***/

            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development",
                "ASPNETCORE_URLS": "http://localhost:5003;https://localhost:5004"   //加入這行設定
            },

            /*** 省略部分代碼 ***/
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach",
            "processId": "${command:pickProcess}"
        }
    ,]
}

如果 Server 是選用IIS,則也可以透過在 web.config 裡加上環境變數ASPNETCORE_URLS來指定起始連結,例如

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritinchildapplications="false">
    <system.webserver>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspnetcore processpath="%LAUNCHER_PATH%" stdoutlogenabled="false" stdoutlogfile=".\logs\stdout" arguments="%LAUNCHER_ARGS%">
        <environmentvariables>
          <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
          <environmentVariable name="ASPNETCORE_URLS" value="http://localhost:5003;https://localhost:5004" />   //加入這行
          <environmentVariable name="ASPNETCORE_HTTPS_PORT" value="443" />
          <environmentVariable name="COMPLUS_ForceENC" value="1" />
        </environmentvariables>
      </aspnetcore>
    </system.webserver>
  </location>
</configuration>


3. 使用指令方式啟動程式並加上 --urls 參數

dotnet run --urls "http://localhost:5003;https://localhost:5004"

此種方式會蓋掉使用環境變數(方法2)的設定


4. 使用 launchSettings.json(只適用開發環境)

在新建一個 ASP.NET Core 專案時,預設都會在主專案下建立一個 Properties 的目錄,裡面可以找到 launchSettings.json 這支檔案,該檔案內容會有個用我們 APP 名稱的區段,裡面有個屬性 applicationUrl,修改成我們想要指定的連結位址即可

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:48135",
      "sslPort": 44311
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MyTestApp": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5004;http://localhost:5003",  //修改成自己想要的位址
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

dotnet run 預設會先自動採用此設定檔的值,優先權高於使用環境變數(方法2)的設定


5. 寫在 appsettings.{ENVIRONMENT}.json

寫在 appsettings.{ENVIRONMENT}.json 設定檔裡算是我比較常用的方式,設定方式如下(請看 Kestrel 區段)

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "Kestrel": {         
    "EndPoints": {
      "Http": {
        "Url": "http://localhost:5003"  /* HTTP */
      },
      "Https": {
        "Url": "https://localhost:5004" /* HTTPS */
      }
    }
  },
  "ConnectionStrings": {
    "MyDbContext": ""
  },
  /*** 省略其它代碼 ***/
}

使用此種方式會覆蓋掉所有以上提到的設定方式(1~4),然後會在 Console 視窗看到類似下面的警告(我是直接忽略) Image


總結 (Summary)

開發環境:建議可採用方法 14

正式(生產)環境:我會在方法 25 之間選擇一種




參考資料

[MSDN] Kestrel web server implementation in ASP.NET Core

[Andrew Lock] 5 ways to set the URLs for an ASP.NET Core app

訪客統計