ASP.NET Core程序要求有一個啟動類。按照慣例,啟動類的名字是 "Startup" 。Startup類負責配置請求管道,處理應用程序的所有請求。你可以指定在Main方法中使用UseStartup<TStartup>()來指定它的名字。啟動類必須包含Configure方法。ConfigureServices方法是可選的。在應用程序啟動的時候它們會被調用。
一、Configure方法
用於指定ASP.NET程序如何應答HTTP請求。它通過添加中間件來配置請求管道到一個IApplicationBuilder實例。IApplicationBuilder實例是由依賴注入提供的。
示例:
在下面默認的網站模板中,一些拓展方法被用於配置管道,支持BrowserLink,錯誤頁,靜態文件,ASP.NET MVC,和Identity。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
二、ConfigureService方法
這個方法是可選的,但必須在Configure方法之前調用, 因為一些features要在連接到請求管道之前被添加。配置選項是在這個方法中設置的。
publicvoidConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
三、參考
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup
原文鏈接:http://www.cnblogs.com/liszt/p/6403870.html