ASP.NET Core 基礎知識之 Startup 類配置

Startup 類配置服務和應用的請求管道。

 

ASP.NET Core 應用使用 Startup 類,按照約定命名爲 Startup。 Startup 類:

1.可選擇性地包括 ConfigureServices 方法以配置應用的服務 。 服務是一個提供應用功的可重用組件。 在 ConfigureServices 中註冊服務,並通過依賴關係注(DI) 或 Application-Services 在整個應用中使用服務 。

2.包括 Configure 方法以創建應用的請求處理管道。

 

在應用啓動時,ASP.NET Core 運行時會調用 ConfigureServices 和 Configure

方法調用順序: Main -> ConfigureServices -> Configure

 

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

        public IConfiguration Configuration { get; }

        //在 ConfigureServices 中註冊服務,並通過依賴關係注入 (DI) 或 ApplicationServices 在整個應用中使用服務
        public void ConfigureServices(IServiceCollection services)
        {
            
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // Configure 方法用以創建應用的請求處理管道。
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

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

}

ConfigureServices 方法:

ConfigureServices 方法:

1.可選。

2.在 Configure方法配置應用服務之前,由主機調用。

3.其中按常規設置配置選項。

 

對於需要大量設置的功能,IServiceCollection 上有 Add{Service} 擴展方法。 例如,AddDbContext、AddDefaultIdentity、AddEntityFrameworkStores 和 AddRazorPages等方法:

public class Startup

{

    public Startup(IConfiguration configuration)

    {

        Configuration = configuration;

    }



    public IConfiguration Configuration { get; }



    public void ConfigureServices(IServiceCollection services)

    {



        services.AddDbContext<ApplicationDbContext>(options =>

            options.UseSqlServer(

                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<IdentityUser>(

            options => options.SignIn.RequireConfirmedAccount = true)

            .AddEntityFrameworkStores<ApplicationDbContext>();



        services.AddRazorPages();

    }

}

執行到Startup的時候,IConfiguration已經被注入到services了,不需要我們額外添加註入

的代碼,但是缺少讀取appsettings.json文件,你可以理解在Startup.cs裏有隱藏的注入代碼

類似如下:

  •  

 
var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddEnvironmentVariables();
Configuration = builder.Build();
services.AddSingleton<IConfiguration>(Configuration);

我們可以使用

使用IOptions,獲取appsetting.json配置文件中的值

例如:appsetting.json中數據爲:

{

  "key1": "KeyVule1",

  "key2": "KeyVule2"

}

  1. 創建appsetting.json對應的類:

    public class appModel
        {
            public string key1 { get; set; }
            public string key2 { get; set; }
        }
    

     

2.在 ConfigureServices中註冊相應的服務:

services.Configure<appModel>(Configuration);

3.在你想要使用的控制器的構造函數中傳遞參數:

  [Route("api/[controller]")]

    [ApiController]

    public class ValuesController : ControllerBase

    {

        public IOptions<appModel> _options;



        public ValuesController(IOptions<appModel> options)

        {

            _options = options;

        }



        // GET api/values

        [HttpGet]

        public ActionResult<IEnumerable<string>> Get()

        {

            return new string[] { _options.Value.key1, _options.Value.key2 };

        }

    }

Configure 方法

Configure 方法用於指定應用響應 HTTP 請求的方式。 可通過將中間件組件添加到 IApplicationBuilder 實例來配置請求管道。 Configure 方法可使用 IApplicationBuilder,但未在服務容器中註冊。 託管創建 IApplicationBuilder 並將其直接傳遞到 Configure

ASP.NET Core 模板配置的管道支持:

  • 開發人員異常頁

  • 異常處理程序

  • HTTP 嚴格傳輸安全性 (HSTS)

  • HTTPS 重定向

  • 靜態文件

  • ASP.NET Core MVC 和 Razor Pages

public class Startup

{

    public Startup(IConfiguration configuration)

    {

        Configuration = configuration;

    }



    public IConfiguration Configuration { get; }



    public void ConfigureServices(IServiceCollection services)

    {

        services.AddRazorPages();

    }



    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

    {

        if (env.IsDevelopment())

        {

            app.UseDeveloperExceptionPage();

        }

        else

        {

            app.UseExceptionHandler("/Error");

            app.UseHsts();

        }



        app.UseHttpsRedirection();

        app.UseStaticFiles();



        app.UseRouting();



        app.UseAuthorization();



        app.UseEndpoints(endpoints =>

        {

            endpoints.MapRazorPages();

        });

    }

}

每個 Use 擴展方法將一個或多箇中間件組件添加到請求管道。例如,UseStaticFiles 配置中間件提供靜態文件。

請求管道中的每個中間件組件負責調用管道中的下一個組件,或在適當情況下使鏈發生短路。

可以在 Configure 方法簽名中指定其他服務,如 IWebHostEnvironment、ILoggerFactory 或 ConfigureServices

中定義的任何內容。如果這些服務可用,則會被注入。

 

微信公衆號:和大家一起成長

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章