標籤:
ASP.NET 5 入門——Application Startup?Startup 類?
在 ASP.NET 5 中,Startup 類是一個應用的進入點,我們可以為不同環境配置不同的內容。
編譯器會尋找專案檔夾下的所有 *.cs 檔案進行編譯,而運行時會尋找所有命名空間下類名為 Startup 的類作為啟動方式。
註解
可以通過設定 project.json 檔案選擇需要(或不需要)編譯的檔案和檔案夾;也可以設定在不同的程式集中搜尋 Startup 類。
Startup 類必須定義一個 Configure 方法,也可以同時定義一個 ConfigureServices 方法。
ConfigureServices 方法?
ConfigureServices 用來定義我們使用了哪些服務,比如MVC、EF、Identity、Logging、Route;也可以自訂一些服務。
下面的例子中,配置了EntityFramework(用於資料訪問,需要在 config.json 中正確設定連接字串)、Identity(用於身分識別驗證/即登入)和MVC。
public void ConfigureServices(IServiceCollection services){ // Add framework services. services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc(); // Add application services. services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>();}
在調用過 ConfigureServices 之後,運行時會調用 Configure 方法。
Configure 方法?
Configure 方法簽名必須包含 IApplicationBuilder 的參數,也可以包含一些其他的五福 IHostingEnvironment 和 ILoggerFactory 的參數。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){ //在控制台中輸出log loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); //在開發環境下,顯示錯誤詳細資料 if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { //否則,導向錯誤頁面 app.UseExceptionHandler("/Home/Error"); // 建立資料庫 try { using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>() .CreateScope()) { serviceScope.ServiceProvider.GetService<ApplicationDbContext>() .Database.Migrate(); } } catch { } } app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear()); //允許訪問wwwroot檔案夾下的靜態檔案 app.UseStaticFiles(); //設定身分識別驗證方式 app.UseIdentity(); // 設定MVC路由 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });}
警告
設定MVC的路由方式必須在 Configure 中設定,僅在 ConfigureServices 中設定是無效的。
ASP.NET 5 入門——Application Startup