ASP.NET Core 基本概念ASP.NET Core fundamentals

ASP.NET Core 應用程式是主控台應用程式,可使用其 Program.Main 方法建立網頁伺服器。An ASP.NET Core app is a console app that creates a web server in its Program.Main method. Main 方法是應用程式的「受控進入點」:The Main method is the app's managed entry point:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

.NET Core 主機:The .NET Core Host:

  • 載入 .NET Core 執行階段Loads the .NET Core runtime.
  • 使用第一個命令列引數做為包含進入點 (Main) 之受控二進位檔案的路徑,並開始執行程式碼。Uses the first command-line argument as the path to the managed binary that contains the entry point (Main) and begins code execution.

Main 方法會叫用 WebHost.CreateDefaultBuilder,這會遵循建立器模式來建立 Web 主機。The Main method invokes WebHost.CreateDefaultBuilder, which follows the builder pattern to create a web host. 建立器具有定義網頁伺服器 (例如 UseKestrel) 和啟動類別 (UseStartup) 的方法。The builder has methods that define a web server (for example, UseKestrel) and the startup class (UseStartup). 以前述範例而言,會自動配置 Kestrel 網頁伺服器。In the preceding example, the Kestrel web server is automatically allocated. 若可行,ASP.NET Core 的 Web 主機會嘗試在 Internet Information Services (IIS) 執行。ASP.NET Core's web host attempts to run on Internet Information Services (IIS), if available. 其他網頁伺服器 (例如 HTTP.sys) 則可透過叫用適當的擴充方法來使用。Other web servers, such as HTTP.sys, can be used by invoking the appropriate extension method. UseStartup啟動章節會進一步說明 UseStartup is explained further in the Startup section.

IWebHostBuilderWebHost.CreateDefaultBuilder 叫用的傳回型別,提供了許多選擇性方法。IWebHostBuilder, the return type of the WebHost.CreateDefaultBuilder invocation, provides many optional methods. 其中某些方法包括用來在 HTTP.sys 中裝載應用程式的 UseHttpSys,以及用於指定根內容目錄的 UseContentRootSome of these methods include UseHttpSys for hosting the app in HTTP.sys and UseContentRoot for specifying the root content directory. BuildRun 方法則會建置 IWebHost 物件,裝載應用程式並開始接聽 HTTP 要求。The Build and Run methods build the IWebHost object that hosts the app and begins listening for HTTP requests.

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

.NET Core 主機:The .NET Core Host:

  • 載入 .NET Core 執行階段Loads the .NET Core runtime.
  • 使用第一個命令列引數做為包含進入點 (Main) 之受控二進位檔案的路徑,並開始執行程式碼。Uses the first command-line argument as the path to the managed binary that contains the entry point (Main) and begins code execution.

Main 方法會使用 WebHostBuilder,這會遵循建立器模式來建立 Web 應用程式主機。The Main method uses WebHostBuilder, which follows the builder pattern to create a web app host. 產生器具有定義網頁伺服器 (例如,UseKestrel) 和啟動類別 (UseStartup) 的方法。The builder has methods that define the web server (for example, UseKestrel) and the startup class (UseStartup). 在上述範例中,會使用 Kestrel 網頁伺服器。In the preceding example, the Kestrel web server is used. 其他網頁伺服器 (例如 HTTP.sys) 則可透過叫用適當的擴充方法來使用。Other web servers, such as HTTP.sys, can be used by invoking the appropriate extension method. UseStartup啟動章節會進一步說明 UseStartup is explained further in the Startup section.

WebHostBuilder 提供許多選擇性方法,包括用來裝載於 IIS 和 IIS Express 中的 UseIISIntegration,以及用於指定根內容目錄的 UseContentRootWebHostBuilder provides many optional methods, including UseIISIntegration for hosting in IIS and IIS Express and UseContentRoot for specifying the root content directory. BuildRun 方法則會建置 IWebHost 物件,裝載應用程式並開始接聽 HTTP 要求。The Build and Run methods build the IWebHost object that hosts the app and begins listening for HTTP requests.

啟動Startup

WebHostBuilder 上的 UseStartup 方法可為應用程式指定 Startup 類別:The UseStartup method on WebHostBuilder specifies the Startup class for your app:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}
public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

Startup 類別是設定應用程式所需之任何服務及定義要求處理管線的位置。The Startup class is where any services required by the app are configured and the request handling pipeline is defined. Startup 必須是公用類別,而且通常包含下列方法。The Startup class must be public and usually contains the following methods. Startup.ConfigureServices 是選擇項。Startup.ConfigureServices is optional.

public class Startup
{
    // This method gets called by the runtime. Use this method
    // to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method
    // to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app)
    {
    }
}
public class Startup
{
    // This method gets called by the runtime. Use this method
    // to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method
    // to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app)
    {
    }
}

ConfigureServices 會定義應用程式所使用的服務 (例如 ASP.NET Core MVC、Entity Framework Core、Identity 等)。ConfigureServices defines the Services used by your app (for example, ASP.NET Core MVC, Entity Framework Core, Identity). Configure 定義在要求管線中呼叫的中介軟體Configure defines the middleware called in the request pipeline.

如需詳細資訊,請參閱ASP.NET Core 中的應用程式啟動For more information, see ASP.NET Core 中的應用程式啟動.

內容根目錄Content root

內容根目錄是應用程式所使用任何內容的基底路徑,例如 Razor 頁面、MVC 檢視和靜態資產。The content root is the base path to any content used by the app, such as Razor Pages, MVC views, and static assets. 根據預設,內容根目錄與裝載應用程式之可執行檔的應用程式基底路徑相同。By default, the content root is the same location as the app base path for the executable hosting the app.

Web 根目錄 (webroot)Web root (webroot)

應用程式的 Web 根目錄是專案中包含公用、靜態資源 (例如 CSS、JavaScript 與影像檔) 的目錄。The webroot of an app is the directory in the project containing public, static resources, such as CSS, JavaScript, and image files. 根據預設,wwwroot 是 webroot。By default, wwwroot is the webroot.

針對 Razor (.cshtml) 檔案,波狀符號斜線 ~/ 指向 webroot。For Razor (.cshtml) files, the tilde-slash ~/ points to the webroot. 開頭為 ~/ 的路徑稱為虛擬路徑。Paths beginning with ~/ are referred to as virtual paths.

相依性插入 (服務)Dependency injection (services)

「服務」是一種在應用程式中常用的元件。A service is a component that's intended for common consumption in an app. 服務可透過相依性插入 (DI) 提供。Services are made available through dependency injection (DI). ASP.NET Core 包含原生逆轉控制 (IoC) 容器,其根據預設支援建構函式插入ASP.NET Core includes a native Inversion of Control (IoC) container that supports constructor injection by default. 您可視需要取代預設容器。You can replace the default container if you wish. DI 除了具有鬆散結合的優點之外,還能夠讓整個應用程式皆可使用服務,例如記錄In addition to its loose coupling benefit, DI makes services, such as logging, available throughout your app.

如需詳細資訊,請參閱.NET Core 中的相依性插入For more information, see .NET Core 中的相依性插入.

中介軟體Middleware

在 ASP.NET Core 中,您可以使用中介軟體來撰寫要求管線。In ASP.NET Core, you compose your request pipeline using middleware. ASP.NET Core 中介軟體會在 HttpContext 上執行非同步作業,然後叫用管線中下一個中介軟體或終止要求。ASP.NET Core middleware performs asynchronous operations on an HttpContext and then either invokes the next middleware in the pipeline or terminates the request.

依照慣例,將稱為 "XYZ" 之中介軟體元件新增至管線的方法是,在 Configure 方法中叫用 UseXYZ 擴充方法。By convention, a middleware component called "XYZ" is added to the pipeline by invoking a UseXYZ extension method in the Configure method.

ASP.NET Core 包含一組豐富的內建中介軟體,您也可以自行撰寫自訂中介軟體。ASP.NET Core includes a rich set of built-in middleware, and you can write your own custom middleware. ASP.NET Core 應用程式支援 Open Web Interface for .NET (OWIN),這可讓 Web 應用程式與網頁伺服器分離。Open Web Interface for .NET (OWIN), which allows web apps to be decoupled from web servers, is supported in ASP.NET Core apps.

如需詳細資訊,請參閱 ASP.NET Core 中介軟體具有 ASP.NET Core 的 Open Web Interface for .NET (OWIN)For more information, see ASP.NET Core 中介軟體 and 具有 ASP.NET Core 的 Open Web Interface for .NET (OWIN).

初始化 HTTP 要求Initiate HTTP requests

IHttpClientFactory 可用來存取 HttpClient 執行個體以發出 HTTP 要求。IHttpClientFactory is available to access HttpClient instances to make HTTP requests.

如需詳細資訊,請參閱初始化 HTTP 要求For more information, see 初始化 HTTP 要求.

環境Environments

「開發」與「生產」等環境是 ASP.NET Core 中的第一級概念,並可使用環境變數、設定檔案和命令列引數加以設定。Environments, such as Development and Production, are a first-class notion in ASP.NET Core and can be set using an environment variable, settings file, and command-line argument.

如需詳細資訊,請參閱在 ASP.NET Core 中使用多個環境For more information, see 在 ASP.NET Core 中使用多個環境.

裝載Hosting

ASP.NET Core 應用程式會設定並啟動主機,其負責啟動應用程式以及管理存留期。ASP.NET Core apps configure and launch a host, which is responsible for app startup and lifetime management.

如需詳細資訊,請參閱<xref:fundamentals/host/index>。For more information, see <xref:fundamentals/host/index>.

伺服器Servers

ASP.NET Core 裝載模型不會直接接聽要求。The ASP.NET Core hosting model doesn't directly listen for requests. 裝載模型需透過 HTTP 伺服器實作,才可將要求轉寄至應用程式。The hosting model relies on an HTTP server implementation to forward the request to the app.

ASP.NET Core 隨附下列伺服器實作:ASP.NET Core provides the following server implementations:

  • Kestrel 伺服器是受控、跨平台的網路伺服器。Kestrel server is a managed, cross-platform web server. Kestrel 通常會使用 IIS在反向 Proxy 設定中執行。Kestrel is often run in a reverse proxy configuration using IIS. Kestrel 也可在 ASP.NET Core 2.0 或更新版本中作為直接向網際網路公開的公眾 Edge Server 執行。Kestrel can also be run as a public-facing edge server exposed directly to the Internet in ASP.NET Core 2.0 or later.
  • IIS HTTP 伺服器 (IISHttpServer) 是 IIS 的同處理序伺服器IIS HTTP Server (IISHttpServer) is an in-process server for IIS.
  • HTTP.sys 伺服器是 Windows 上的 ASP.NET Core 網頁伺服器。HTTP.sys server is a web server for ASP.NET Core on Windows.

ASP.NET Core 隨附下列伺服器實作:ASP.NET Core provides the following server implementations:

  • Kestrel 伺服器是受控、跨平台的網路伺服器。Kestrel server is a managed, cross-platform web server. Kestrel 通常會使用 IIS在反向 Proxy 設定中執行。Kestrel is often run in a reverse proxy configuration using IIS. Kestrel 也可在 ASP.NET Core 2.0 或更新版本中作為直接向網際網路公開的公眾 Edge Server 執行。Kestrel can also be run as a public-facing edge server exposed directly to the Internet in ASP.NET Core 2.0 or later.
  • HTTP.sys 伺服器是 Windows 上的 ASP.NET Core 網頁伺服器。HTTP.sys server is a web server for ASP.NET Core on Windows.

如需詳細資訊,請參閱ASP.NET Core 中的網頁伺服器實作For more information, see ASP.NET Core 中的網頁伺服器實作.

ConfigurationConfiguration

ASP.NET Core 會使用以成對的名稱/值為基礎的組態模型。ASP.NET Core uses a configuration model based on name-value pairs. 而非以 System.Configurationweb.config 為基礎的組態模型。組態會從組態提供者經排序的集合中取得設定。The configuration model isn't based on System.Configuration or web.config. Configuration obtains settings from an ordered set of configuration providers. 內建的組態提供者支援各種檔案格式 (XML、JSON、INI)、環境變數和命令列引數。The built-in configuration providers support a variety of file formats (XML, JSON, INI), environment variables, and command-line arguments. 您也可以撰寫您自己的自訂組態提供者。You can also write your own custom configuration providers.

如需詳細資訊,請參閱ASP.NET Core 的設定For more information, see ASP.NET Core 的設定.

記錄Logging

ASP.NET Core 支援可搭配各種記錄提供者的記錄 API。ASP.NET Core supports a Logging API that works with a variety of logging providers. 內建提供者支援將記錄檔傳送至一或多個目的地。Built-in providers support sending logs to one or more destinations. 可以使用協力廠商記錄架構。Third-party logging frameworks can be used.

如需詳細資訊,請參閱ASP.NET Core 中的記錄For more information, see ASP.NET Core 中的記錄.

錯誤處理Error handling

ASP.NET Core 具有內建案例,可處理應用程式中的錯誤,包括開發人員例外狀況頁面、自訂錯誤頁面、靜態狀態碼頁面,以及啟動例外狀況處理。ASP.NET Core has built-in scenarios for handling errors in apps, including a developer exception page, custom error pages, static status code pages, and startup exception handling.

如需詳細資訊,請參閱處理 ASP.NET Core 中的錯誤For more information, see 處理 ASP.NET Core 中的錯誤.

路由Routing

ASP.NET Core 提供用來將應用程式要求路由至路由處理常式的案例。ASP.NET Core offers scenarios for routing of app requests to route handlers.

如需詳細資訊,請參閱ASP.NET Core 中的路由For more information, see ASP.NET Core 中的路由.

背景工作Background tasks

背景工作會實作為託管服務Background tasks are implemented as hosted services. 託管服務是具有背景工作邏輯的類別,可實作 IHostedService 介面。A hosted service is a class with background task logic that implements the IHostedService interface.

如需詳細資訊,請參閱在 ASP.NET Core 中使用託管服務的背景工作For more information, see 在 ASP.NET Core 中使用託管服務的背景工作.

存取 HttpContextAccess HttpContext

在使用 Razor 頁面和 MVC 處理要求時,會自動提供 HttpContextHttpContext is automatically available when processing requests with Razor Pages and MVC. HttpContext 尚無法使用的情況下,您可以透過 IHttpContextAccessor 介面及其預設實作 HttpContextAccessor 存取 HttpContextIn circumstances where HttpContext isn't readily available, you can access the HttpContext through the IHttpContextAccessor interface and its default implementation, HttpContextAccessor.

如需詳細資訊,請參閱存取 ASP.NET Core 中的 HttpContextFor more information, see 存取 ASP.NET Core 中的 HttpContext.