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

本文是了解如何開發 ASP.NET Core 應用程式的關鍵主題概觀。This article is an overview of key topics for understanding how to develop ASP.NET Core apps.

Startup 類別The Startup class

Startup 類別是:The Startup class is where:

  • 已設定應用程式所需的服務。Services required by the app are configured.
  • 定義要求處理管線的位置。The request handling pipeline is defined.

「服務」 是應用程式所使用的元件。Services are components that are used by the app. 例如,記錄元件即為一項服務。For example, a logging component is a service. 設定 (或「註冊」 ) 服務的程式碼會新增至 Startup.ConfigureServices 方法。Code to configure (or register) services is added to the Startup.ConfigureServices method.

要求處理管線由一系列中介軟體元件所組成。The request handling pipeline is composed as a series of middleware components. 例如,中介軟體可能會處理靜態檔案的要求,或是將 HTTP 要求重新導向至 HTTPS。For example, a middleware might handle requests for static files or redirect HTTP requests to HTTPS. 每個中介軟體會在 HttpContext 上執行非同步操作,然後叫用管線中下一個中介軟體或終止要求。Each middleware performs asynchronous operations on an HttpContext and then either invokes the next middleware in the pipeline or terminates the request. 設定要求處理管線的程式碼會新增至 Startup.Configure 方法。Code to configure the request handling pipeline is added to the Startup.Configure method.

以下是 Startup 類別範例:Here's a sample Startup class:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddDbContext<MovieContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MovieDb")));
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseMvc();
    }
}

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

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

ASP.NET Core 具有內建的相依性插入 (DI) 架構,可讓應用程式的類別使用所設定服務。ASP.NET Core has a built-in dependency injection (DI) framework that makes configured services available to an app's classes. 取得類別中一項服務執行個體的其中一種方式,便是使用所需類型的參數來建立建構函式。One way to get an instance of a service in a class is to create a constructor with a parameter of the required type. 參數可以是服務類型或是介面。The parameter can be the service type or an interface. DI 系統會在執行階段提供服務。The DI system provides the service at runtime.

以下是使用 DI 取得 Entity Framework Core 內容物件的類別。Here's a class that uses DI to get an Entity Framework Core context object. 醒目提示的那一行便是建構函式插入的範例:The highlighted line is an example of constructor injection:

public class IndexModel : PageModel
{
    private readonly RazorPagesMovieContext _context;

    public IndexModel(RazorPagesMovieContext context)
    {
        _context = context;
    }
    // ...
    public async Task OnGetAsync()
    {
        var movies = from m in _context.Movies
                        select m;
        Movies = await movies.ToListAsync();
    }
}

雖然 DI 為內建,但其設計用於讓您插入協力廠商的控制反轉 (IoC) 容器 (若您想要的話)。While DI is built in, it's designed to let you plug in a third-party Inversion of Control (IoC) container if you prefer.

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

中介軟體Middleware

要求處理管線是以一系列中介軟體元件組成。The request handling pipeline is composed as a series of middleware components. 每個元件會在 HttpContext 上執行非同步操作,然後叫用管線中下一個中介軟體或終止要求。Each component performs asynchronous operations on an HttpContext and then either invokes the next middleware in the pipeline or terminates the request.

依照慣例,中介軟體元件會透過叫用其 Startup.Configure 方法中的 Use... 延伸模組方法來新增至管線。By convention, a middleware component is added to the pipeline by invoking its Use... extension method in the Startup.Configure method. 例如,若要啟用靜態檔案轉譯,請呼叫 UseStaticFilesFor example, to enable rendering of static files, call UseStaticFiles.

下列範例中醒目提示的程式碼會設定要求處理管線:The highlighted code in the following example configures the request handling pipeline:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddDbContext<MovieContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MovieDb")));
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseMvc();
    }
}

ASP.NET Core 包含一組豐富的內建中介軟體,您也可以撰寫自訂中介軟體。ASP.NET Core includes a rich set of built-in middleware, and you can write custom middleware.

如需詳細資訊,請參閱 ASP.NET Core 中介軟體For more information, see ASP.NET Core 中介軟體.

主機Host

ASP.NET Core 應用程式會在啟動時建置一個「主機」 。An ASP.NET Core app builds a host on startup. 主機是封裝所有應用程式資源的物件,例如:The host is an object that encapsulates all of the app's resources, such as:

  • HTTP 伺服器實作An HTTP server implementation
  • 中介軟體元件Middleware components
  • 記錄Logging
  • DIDI
  • ConfigurationConfiguration

在單一物件中包含所有應用程式相互依存資源的主要理由便是生命週期管理:控制應用程式的啟動及順利關機。The main reason for including all of the app's interdependent resources in one object is lifetime management: control over app startup and graceful shutdown.

可以使用兩種主機:一般主機與 Web 主機。Two hosts are available: the Generic Host and the Web Host. 建議您使用一般主機,Web 主機只適用於回溯相容性。The Generic Host is recommended, and the Web Host is available only for backwards compatibility.

建立主機的程式碼位於 Program.Main 中:The code to create a host is in Program.Main:

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>();
            });
}

CreateDefaultBuilderConfigureWebHostDefaults 方法會設定具備一般常用選項的主機,如下所示:The CreateDefaultBuilder and ConfigureWebHostDefaults methods configure a host with commonly used options, such as the following:

  • 使用 Kestrel 作為網頁伺服器,並啟用 IIS 整合。Use Kestrel as the web server and enable IIS integration.
  • appsettings.jsonappsettings.{Environment Name}.json、環境變數與命令列引數載入設定。Load configuration from appsettings.json, appsettings.{Environment Name}.json, environment variables, command line arguments, and other configuration sources.
  • 將記錄輸出傳送到主控台及偵錯提供者。Send logging output to the console and debug providers.

如需詳細資訊,請參閱 .NET 泛型主機For more information, see .NET 泛型主機.

可以使用兩種主機:Web 主機與一般主機。Two hosts are available: the Web Host and the Generic Host. 在 ASP.NET Core 2.x 中,一般主機僅適用於非 Web 案例。In ASP.NET Core 2.x, the Generic Host is only for non-web scenarios.

建立主機的程式碼位於 Program.Main 中:The code to create a host is in Program.Main:

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

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

CreateDefaultBuilder 方法會設定具備一般常用選項的主機,如下所示:The CreateDefaultBuilder method configures a host with commonly used options, such as the following:

  • 使用 Kestrel 作為網頁伺服器,並啟用 IIS 整合。Use Kestrel as the web server and enable IIS integration.
  • appsettings.jsonappsettings.{Environment Name}.json、環境變數與命令列引數載入設定。Load configuration from appsettings.json, appsettings.{Environment Name}.json, environment variables, command line arguments, and other configuration sources.
  • 將記錄輸出傳送到主控台及偵錯提供者。Send logging output to the console and debug providers.

如需詳細資訊,請參閱 ASP.NET Core Web 主機For more information, see ASP.NET Core Web 主機.

非 Web 案例Non-web scenarios

一般主機允許其他類型的應用程式,使用交叉剪輯架構延伸模組,例如記錄、相依性插入 (DI)、設定與應用程式存留期管理。The Generic Host allows other types of apps to use cross-cutting framework extensions, such as logging, dependency injection (DI), configuration, and app lifetime management. 如需詳細資訊,請參閱 .NET 泛型主機在 ASP.NET Core 中使用託管服務的背景工作For more information, see .NET 泛型主機 and 在 ASP.NET Core 中使用託管服務的背景工作.

伺服器Servers

ASP.NET Core 應用程式使用 HTTP 伺服器實作來接聽 HTTP 要求。An ASP.NET Core app uses an HTTP server implementation to listen for HTTP requests. 伺服器會把向應用程式發出的要求作為一組要求功能,合併成一個 HttpContextThe server surfaces requests to the app as a set of request features composed into an HttpContext.

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

  • Kestrel 是跨平台的網頁伺服器。Kestrel is a cross-platform web server. Kestrel 通常會使用 IIS在反向 Proxy 設定中執行。Kestrel is often run in a reverse proxy configuration using IIS. 在 ASP.NET Core 2.0 或更新版本中,Kestrel 可以作為直接向網際網路公開的公眾 Edge Server 執行。In ASP.NET Core 2.0 or later, Kestrel can be run as a public-facing edge server exposed directly to the Internet.
  • IIS HTTP 伺服器則是適用於使用 IIS Windows 的伺服器。IIS HTTP Server is a server for windows that uses IIS. 透過此伺服器,ASP.NET Core 應用程式及 IIS 便可以在相同處理序中執行。With this server, the ASP.NET Core app and IIS run in the same process.
  • HTTP.sys 則是適用於並未搭配 IIS 使用 Windows 的伺服器。HTTP.sys is a server for Windows that isn't used with IIS.

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

  • Kestrel 是跨平台的網頁伺服器。Kestrel is a cross-platform web server. Kestrel 通常會使用 IIS在反向 Proxy 設定中執行。Kestrel is often run in a reverse proxy configuration using IIS. 在 ASP.NET Core 2.0 或更新版本中,Kestrel 可以作為直接向網際網路公開的公眾 Edge Server 執行。In ASP.NET Core 2.0 or later, Kestrel can be run as a public-facing edge server exposed directly to the Internet.
  • HTTP.sys 則是適用於並未搭配 IIS 使用 Windows 的伺服器。HTTP.sys is a server for Windows that isn't used with IIS.

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

ConfigurationConfiguration

ASP.NET Core 提供組態架構,可從組態提供者的已排序集合中,以成對名稱和數值的形式取得設定。ASP.NET Core provides a configuration framework that gets settings as name-value pairs from an ordered set of configuration providers. 您可以使用各種來源的內建組態提供者,例如 .json 檔案、 .xml 檔案、環境變數及命令列引數。There are built-in configuration providers for a variety of sources, such as .json files, .xml files, environment variables, and command-line arguments. 您也可以撰寫自訂組態提供者。You can also write custom configuration providers.

例如,您可以指定組態來自 appsettings.json 和環境變數。For example, you could specify that configuration comes from appsettings.json and environment variables. 然後當要求 ConnectionString 的值時,架構便會先在 appsettings.json 檔案中尋找。Then when the value of ConnectionString is requested, the framework looks first in the appsettings.json file. 若有找到值,但在環境變數中也存在該值,則會優先使用來自環境變數的值。If the value is found there but also in an environment variable, the value from the environment variable would take precedence.

針對管理保密組態資料 (例如密碼),ASP.NET Core 提供祕密管理員工具For managing confidential configuration data such as passwords, ASP.NET Core provides a Secret Manager tool. 針對生產祕密,我們建議使用 Azure Key VaultFor production secrets, we recommend Azure Key Vault.

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

選項Options

在可能的情況下,ASP.NET Core 會遵循「選項模式」 來儲存及擷取組態值。Where possible, ASP.NET Core follows the options pattern for storing and retrieving configuration values. 選項模式使用類別來代表一組相關的設定。The options pattern uses classes to represent groups of related settings.

例如,下列程式碼會設定 WebSocket 選項:For example, the following code sets WebSockets options:

var options = new WebSocketOptions  
{  
   KeepAliveInterval = TimeSpan.FromSeconds(120),  
   ReceiveBufferSize = 4096
};  
app.UseWebSockets(options);

如需詳細資訊,請參閱 ASP.NET Core 中的選項模式For more information, see ASP.NET Core 中的選項模式.

環境Environments

執行環境 (例如「開發」 、「預備」 及「生產」 ) 是 ASP.NET Core 中的第一級概念。Execution environments, such as Development, Staging, and Production, are a first-class notion in ASP.NET Core. 您可以透過設定 ASPNETCORE_ENVIRONMENT 環境變數,指定應用程式執行的環境。You can specify the environment an app is running in by setting the ASPNETCORE_ENVIRONMENT environment variable. ASP.NET Core 會在應用程式啟動時讀取環境變數,然後將值儲存在 IHostingEnvironment 實作中。ASP.NET Core reads that environment variable at app startup and stores the value in an IHostingEnvironment implementation. 環境物件可在應用程式中的任何位置,透過 DI 使用。The environment object is available anywhere in the app via DI.

下列 Startup 類別的範例程式碼會設定應用程式,只在於「開發」環境中執行時提供詳細的錯誤資訊:The following sample code from the Startup class configures the app to provide detailed error information only when it runs in development:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseMvc();
}

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

記錄Logging

ASP.NET Core 支援記錄 API,此 API 能與各種內建和第三方記錄提供者搭配使用。ASP.NET Core supports a logging API that works with a variety of built-in and third-party logging providers. 可用的提供者包括如下:Available providers include the following:

  • 主控台Console
  • 偵錯Debug
  • Windows 上的事件追蹤Event Tracing on Windows
  • Windows 事件記錄檔Windows Event Log
  • TraceSourceTraceSource
  • Azure App ServiceAzure App Service
  • Azure Application InsightsAzure Application Insights

透過從 DI 取得 ILogger 物件並呼叫記錄方法,從應用程式程式碼中的任何位置寫入記錄。Write logs from anywhere in an app's code by getting an ILogger object from DI and calling log methods.

以下是使用 ILogger 物件的範例程式碼,其中建構函式插入及記錄方法呼叫都已醒目提示。Here's sample code that uses an ILogger object, with constructor injection and the logging method calls highlighted.

public class TodoController : ControllerBase
{
    private readonly ILogger _logger;

    public TodoController(ILogger<TodoController> logger)
    {
        _logger = logger;
    }

    [HttpGet("{id}", Name = "GetTodo")]
    public ActionResult<TodoItem> GetById(string id)
    {
        _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
        // Item lookup code removed.
        if (item == null)
        {
            _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
            return NotFound();
        }
        return item;
    }
}

ILogger 介面可讓您將任何數量的欄位傳遞給記錄提供者。The ILogger interface lets you pass any number of fields to the logging provider. 欄位常用於建構訊息字串,但提供者也可以將它們作為個別欄位,傳送至資料存放區。The fields are commonly used to construct a message string, but the provider can also send them as separate fields to a data store. 這項功能可讓記錄提供者實作 semantic logging (語意記錄),又稱為 structured logging (結構化記錄)This feature makes it possible for logging providers to implement semantic logging, also known as structured logging.

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

路由Routing

「路由」 是一種對應到處理常式的 URL 模式。A route is a URL pattern that is mapped to a handler. 處理常式通常是 Razor 頁面、MVC 控制器中的動作方法,或是中介軟體。The handler is typically a Razor page, an action method in an MVC controller, or a middleware. ASP.NET Core 路由可讓您控制您應用程式使用的 URL。ASP.NET Core routing gives you control over the URLs used by your app.

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

錯誤處理Error handling

ASP.NET Core 具有處理錯誤的內建功能,例如:ASP.NET Core has built-in features for handling errors, such as:

  • 開發人員例外狀況頁面A developer exception page
  • 自訂錯誤頁面Custom error pages
  • 靜態狀態碼頁面Static status code pages
  • 啟動例外狀況處理Startup exception handling

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

發出 HTTP 要求Make HTTP requests

IHttpClientFactory 的實作可用於建立 HttpClient 執行個體。An implementation of IHttpClientFactory is available for creating HttpClient instances. Factory:The factory:

  • 提供一個集中位置以便命名和設定邏輯 HttpClient 執行個體。Provides a central location for naming and configuring logical HttpClient instances. 例如,您可以註冊 github 並設定用戶端以存取 GitHub。For example, a github client can be registered and configured to access GitHub. 預設用戶端可以註冊用於其他用途。A default client can be registered for other purposes.
  • 支援註冊及多個委派處理常式的鏈結,以用於建置傳出要求中介軟體管線。Supports registration and chaining of multiple delegating handlers to build an outgoing request middleware pipeline. 此模式與 ASP.NET Core 中的輸入中介軟體管線相似。This pattern is similar to the inbound middleware pipeline in ASP.NET Core. 模式提供一個機制來管理 HTTP 要求的跨領域關注,包括快取、錯誤處理、序列化和記錄。The pattern provides a mechanism to manage cross-cutting concerns around HTTP requests, including caching, error handling, serialization, and logging.
  • Polly 整合,Polly 是一種熱門的協力廠商程式庫,用於進行暫時性的錯誤處理。Integrates with Polly, a popular third-party library for transient fault handling.
  • 管理基礎 HttpClientMessageHandler 執行個體的共用和存留期,以避免在手動管理 HttpClient 存留期時,發生的常見 DNS 問題。Manages the pooling and lifetime of underlying HttpClientMessageHandler instances to avoid common DNS problems that occur when manually managing HttpClient lifetimes.
  • 針對透過處理站所建立之用戶端傳送的所有要求,新增可設定的記錄體驗 (透過 ILogger)。Adds a configurable logging experience (via ILogger) for all requests sent through clients created by the factory.

如需詳細資訊,請參閱 在 ASP.NET Core 中使用 IHttpClientFactory 發出 HTTP 要求For more information, see 在 ASP.NET Core 中使用 IHttpClientFactory 發出 HTTP 要求.

內容根目錄Content root

內容根是指向任何由應用程式所使用私人內容的基礎路徑,例如其 Razor 檔案。The content root is the base path to any private content used by the app, such as its Razor files. 根據預設,內容根是裝載應用程式可執行檔的基礎路徑。By default, the content root is the base path for the executable hosting the app. 您可以在建置主機時指定替代位置。An alternative location can be specified when building the host.

如需詳細資訊,請參閱內容根For more information, see Content root.

如需詳細資訊,請參閱內容根For more information, see Content root.

Web 根目錄Web root

Web 根目錄 (也稱為 webroot) 是公用、靜態資源 (例如 CSS、JavaScript 和影像檔) 的基礎路徑。The web root (also known as webroot) is the base path to public, static resources, such as CSS, JavaScript, and image files. 根據預設,靜態檔案中介軟體只會提供來自 Web 根目錄 (及其子目錄) 的檔案。The static files middleware will only serve files from the web root directory (and sub-directories) by default. Web 根目錄路徑預設為 {內容根}/wwwroot,但您可以在建置主機時指定不同的位置。The web root path defaults to {Content Root}/wwwroot, but a different location can be specified when building the host.

在 Razor ( .cshtml) 檔案中,波狀符號與正斜線 ~/ 會指向 Web 根目錄。In Razor (.cshtml) files, the tilde-slash ~/ points to the web root. 開頭為 ~/ 的路徑稱為虛擬路徑。Paths beginning with ~/ are referred to as virtual paths.

如需詳細資訊,請參閱 ASP.NET Core 中的靜態檔案For more information, see ASP.NET Core 中的靜態檔案.