使用 .Net Core CLI 和 VS Code 開發 ASP.NET Core 2.0

  • 2034
  • 0

這一篇文章是很簡單的 hands on,主要說明不使用 Visual Studio 2017 的情況下,只用 Visual Studio Code 搭配 .Net Core CLI 來進行 .Net 程式開發.本文以 ASP.NET Core 2.0 為說明用的範本.若你願意動手跟著文章的內容做,請先安裝目前最新版的 .Net Core SDKVisual Studio Code

Step 1: 開始一個 command prompt,別用管理者身份去執行.

Step 2: 建立一個目錄叫 ASPNETCore2Demo

Step 3: 執行 dontet new sln,這指令會建立一個 VS 用的 solution file,檔名就是目錄名稱 ASPNETCore2Demo.sln

Step 4: 執行 code .  (注意,有一個 "點",用來開始目前的目錄)

Step 5: 回到 command prompt,輸入下列指令

md WebApp
cd WebApp
dotnet new mvc

建立一個名為 WebApp 的目錄,並在這目錄下透過 dotnet.exe 建立一個 ASP.NET Core MVC 的範本,同時範本所需的 package 也會同時被 restore.所以在這指令完成的最後你會看到 "Restore succeeded" 的字.

Step 6: 執行 dotnet run,你會看到如下的字樣,

到目前為止,你已經知道如何使用 dotnet.exe 建立 MVC 範本以及執行這個專案.按下 Ctrl+C 來停止該專案後,接著來建立一個 Class Library.

Step 7: 在 command prompt 中,回到  ASPNETCore2Demo 目錄,並且執行以下的指令

md ClassLibrary
cd ClassLibrary
dotnet new classlib

這將透過 dotnet.exe 建立一個 Class Library 的範本.

Step 8: 回到 Visual Studio Code,開始 Class Library 下的 Class1.cs  檔案,並且下列的程式碼貼在裡面.

public string GetHello() {
    return "Hello from class library";
}

Step 9: 回到 command prompt,將目錄切換到 WebApp 並執行下列指令

dotnet add reference ..\ClassLibrary\ClassLibrary.csproj

這指令把 ClassLibrary 加入到 WebApp 的 References 之中.

Step 10: 回到  command prompt,將目錄切換到 ASPNETCore2Demo,然後輸入以下指令

dotnet sln add WebApp\WebApp.csproj
dotnet sln add ClassLibrary\ClassLibrary.csproj

這指令將兩個專案檔加入到先前建立的 solution.

Step 11: 回到 Visual Studio Code,在 WebApp 下找到 HomeController.cs,然後把 About() 改成如下

public IActionResult About()
{
    ClassLibrary.Class1 c = new ClassLibrary.Class1();
    ViewData["Message"] = "Your application description page. "  + c.GetHello();
    return View();
}

Step 12: 回到 command prompt 在 ASPNETCore2Demo 路徑下輸入以下指令

dotnet build
cd WebApp
dotnet run

這指令會 build 整個 solution,然後再將此 ASP.NET MVC 專案執行起來.當你用瀏覽器到 http://localhost:5000 並按下畫面上的 About 時,你就會看到之前在 Class Library 加的字串已經能顯示在這.

Step 13. 回到 command prompt 按下 Ctrl+C 停止專案執行. Step 13: 回到 command prompt,輸入以下的指令:

dotnet publish -o ..\output

這指令會將整個專案程式所需要的檔案 (dll, json, css, html等等) 都輸出到 output 目錄中,其中 output 目錄是在你目前目錄的上一層.當你將路徑切換到 output 下時,你會看到 WebApp.dll, ClassLibrary.dll, wwwroot 目錄, web.config,以及其他相關的目錄與 json 檔案.這些內容就是你可以上傳到 IIS 或 Azure 上執行時所需要的內容.因為此 MVC 的範本是 ASP.NET Core shared application,所以你會看到你的網站程式是 WebApp.dll,而不是 WebApp.exe.如果你在 WebApp.csproj 裡面把 RuntimeIdentifier 加上去並指定 win10-x86 or win10-x64 時,則你就會看到的是 WebApp.exe 而不是 WebApp.dll,因此此時這個 ASP.NET Core 專案已經變成 Standalone 型式.有關 ASP.NET Core Share vs. Standalone 的內容,你可以參考我之前寫過的一篇文章

Step 14: 將 command prompt 切換到 output 目錄下,執行 dotnet WebApp.dll,此時你就會看到網站已經跑起來了. 這是一篇很簡單的文章主要是用來說明 dotnet.exe 已經可以為你做許多的事情,透過以上的步驟你也可以發現在不需要使用 Visual Studio 2017 的情況下,你也是可以利用 dotnet.exe 搭配 Visual Studio Code 來進行 .Net 程式開發.