1. 程式人生 > 其它 >.NET Core中Startup.cs檔案的作用

.NET Core中Startup.cs檔案的作用

我們在建立.net core專案中Startup.cs檔案必不可少,最近在面試中別人提問到Startup.cs中有哪三種方法,以及對應的作用是什麼,沒有答覆的很好,因此也總結記錄一下。

以前我們在建立.net專案的時候會看到兩個檔案:

  1. global.asax 檔案,可以在啟動 Web 應用程式期間編寫程式碼來執行的一個地方
  2. web.config 檔案,用來包含應用程式需要執行的所有配置引數

在 ASP.NET Core 中,這些檔案全部消失,取而代之的是使用 Startup.cs 載入配置和啟動程式碼

Startup.cs 檔案中有一個 Startup 類,在這個類中可以配置應用程式,甚至配置配置源

下面先看看原檔案的結構

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

namespace HelloWorld
{
    public class Startup
    {
        // 該方法在執行時被呼叫。
        // 可以使用該方法將服務新增到容器中
        // 更多資訊配置應用程式的資訊,可以檢視 https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // 該方法在執行時被呼叫
        // 可以使用該方法來配置 HTTP 請求管道
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
}

Startup類裡面必須公開包含兩個方法以及一個建構函式:

1、ConfigureServices()

public void ConfigureServices(IServiceCollection services){}

用於定義應用程式所需要的服務的地方,比如我們所說的注入各種服務就是在這裡

2、Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env){}

用於定義請求管道中的中介軟體,app.Run方法設定的地方

3、還有一個是Startup本身的一個建構函式,加上之後有三個方法。

  public Startup() 
        { 
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("AppSettings.json"); 
            Configuration = builder.Build(); 
        }

示例:將HolleWord!輸出改成從配置檔案中獲取內容並輸出

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

namespace HelloWorld
{
    public class Startup
    {
        public Startup() 
        { 
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("AppSettings.json"); 
            Configuration = builder.Build(); 
        }

        public IConfiguration Configuration { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        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, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                var msg = Configuration["message"];
                await context.Response.WriteAsync(msg);
            });
        }
    }
}