ASP.NET Core学习——2

Application Startup

ASP.NET Core为应用程序提供了处理每个请求的完整控制。Startup类是应用程程的入口(entry point),这个类可以设置配置(configuration),并且将应用程序将要使用的服务连接起来。

开发人员可以在Startup类中配置请求管道,该管道将用于处理应用程序的所有请求。

1.Startup类

在ASP.NET Core中,Startup类提供了应用程序的入口,而且在所有应用程序中都有Startup类。

Startup类能够选择性地在构造函数中接受通过依赖注入提供的依赖项。

Startup类必须定义Configure方法,可选择定义一个ConfigureServices方法,这些方法将在应用程序启动时被调用。

2.Configure方法

Configure方法用于指定ASP.NET应用程序将如何响应每一个HTTP请求。

复杂的管道配置可以封装于中间件(middleware)中,并通过扩展方法添加到IApplicationBuilder上。

Configure方法必须接受一个Configure参数。一些额外服务,比如IHostingEnvironment或ILoggerFactory也可以被指定,并且在它们可用的情况下,这些服务将会被服务器注入进来。

下面的例子中,多个扩展方法被用于配置管道,以支持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.UseDirectoryBrowser();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseIdentity();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name:"default",
                    template:"{controller=Home}/{action=Index}/{id?}"
                    );
            });
        }

每个Use扩展方法都会把一个中间件加入请求管道。例如,UseMvc扩展方法增加了路由中间件请求管道,并配置MVC为默认处理程序。

3.ConfigureServices

正如Configure,建议在IServiceCollection上使用扩展方法来包装需要大量配置细节的ConfigureServices。

下面的例子中看到几个Add[Something]扩展方法被用于设置应用程序,以能够使用Entity Framework、Identity和MVC

        public void ConfigureServices(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>();
        }

通过依赖注入可将服务加入服务容器,使其在应用程序中可用。