.NET Core 可以建立Web及桌面應用程式,本篇筆記記錄 ASP.NET Core 建立 Web 應用程式時的基礎概念。
建立專案
使用dotnet new web
指令由範本建立專案後,可以觀察到資料夾內多了一些檔案和目錄。
Foo
|--appsettings.json //用於設定連線字串、key或可能會變動的資訊
|--bin //存放編譯過後的程式碼和DLL檔案
|--Foo.csproj //C#專案的專案設定檔
|--Program.cs //主程式(程式進入點)
|--Properties
|--launchSettings.json //程式的啟動設定
進入點
其中程式進入點是一個名為Program.cs
的檔案,檔案內預設會包含以下程式碼:
namespace Foo;
public class Program
{
public static void Main(string[] args)
{
// 回傳一個類別為WebApplicationBuilder的物件,名稱為builder
var builder = WebApplication.CreateBuilder(args);
// 建置WebApplication,回傳WebApplication的物件
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
// 執行應用程式
app.Run();
}
}
使用WebApplication.CreateBuilder
可以建立一個WebApplicationBuilder的物件,該物件包含許多屬性,例如用於管理服務的Services、用於記錄的Logging或是與設定相關的Configuration等,可以在需要時取用這些屬性。
builder物件的Build()
方法會建置並回傳WebApplication物件,該物件可以設定路由或請求的pipeline。ASP.NET Core 提供許多現成的Middleware可以使用,例如常見的UseAuthentication()
、MapControllers()
或UseRouting()
等,使用Use()
方法也可以加入自定義的Middleware。除了設定Middleware與路由外,在程式的最後執行Run()
或其他相關的方法可以啟動應用程式。
啟動設定
launchSettings.json
是用來決定執行應用程式時所要套用的環境設定,使用範本建立的ASP.NET Core專案預設包含以下設定:
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:42581",
"sslPort": 44374
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5159",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7084;http://localhost:5159",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
檔案中的profiles區塊包含http、https及IIS Express三個設定,其中.NET CLI只支援commandName為Project的設定,其餘commandName設定為IIS Express、IIS或Executable皆無法以.NET CLI指定其作為啟動設定。
專案設定檔
目錄中的.csproj檔案是C#專案的專案設定檔,檔案內包含MSBuild建置專案時所需的資訊,例如程式建置時所需包含的檔案、程式版本、引用到的函式庫或專案等,可視需求加入所需的設定。