解釋 ASP.NET Core 中 Startup 類的作用


Startup 類配置應用程式的服務並定義中介軟體管道。

一般來說,Program 類用於配置應用程式的基礎設施,例如 HTTP 伺服器、與 IIS 的整合以及配置源。相反,Startup 類定義應用程式使用的元件和功能以及應用程式的中介軟體管道。

Startup.cs

這是一個標準 ASP.NET Core 應用程式中的 Startup.cs 檔案示例。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace TutorialsPoint{
   public class Startup{
      public Startup(IConfiguration configuration){
         Configuration = configuration;
      }

      public IConfiguration Configuration { get; }

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

      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
         if (env.IsDevelopment()){
            app.UseDeveloperExceptionPage();
         }
         else{
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
         }
         app.UseHttpsRedirection();
         app.UseStaticFiles();

         app.UseRouting();

         app.UseAuthorization();

         app.UseEndpoints(endpoints =>{
            endpoints.MapControllerRoute(
               name: "default",
               pattern: "{controller=Home}/{action=Index}/{id?}");
         });
      }
   }
}

Startup 類包含兩個方法

  • ConfigureServices():註冊應用程式所需的服務。

  • Configure():配置中介軟體管道,控制應用程式如何處理 HTTP 請求併發送響應。

服務

服務是模組化的、鬆散耦合的元件,專注於完成一項任務,例如快取、身份驗證等。在 ASP.NET Core 中,服務只是提供特定功能給應用程式的 C# 類。

您可以使用第三方 Nuget 庫提供的服務,也可以自己編寫服務。無論在哪裡建立,都必須在 ConfigureServices() 方法中進行配置。

Startup 類使用 IServiceCollection 來儲存應用程式所需的所有服務。它還配置依賴注入 (DI)。因此,這些服務將由 DI 容器自動注入到您的程式碼中。

中介軟體

中介軟體定義應用程式如何處理傳入的 HTTP 請求。它還處理傳出的 HTTP 響應。

中介軟體由按順序執行的小模組組成,這些模組可以轉換傳入的請求或傳出的響應。中介軟體可以執行各種任務,包括日誌記錄、身份驗證和授權、服務靜態檔案、錯誤處理等。

需要注意的是,中介軟體的順序很重要。ASP.NET Core 框架按您定義的順序執行中介軟體程式碼。

 


更新於:2021年6月22日

4K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.