ASP.NET Core 1.0 入门——Application Startup

来源:互联网 发布:广东广电网络 机顶盒 编辑:程序博客网 时间:2024/06/05 00:03

提示

更新时间:2016年01月20日。

Startup 类

在 ASP.NET Core 1.0 中,Startup 类是一个应用的入口点,我们可以为不同环境配置不同的内容。

编译器会查找项目文件夹下的所有 *.cs 文件进行编译,而运行时会寻找所有命名空间下类名为 Startup 的类作为启动方式。

注解

可以通过设置 project.json 文件选择需要(或不需要)编译的文件和文件夹;也可以设置在不同的程序集中搜索 Startup 类。

Startup 类必须定义一个 Configure 方法,也可以同时定义一个 ConfigureServices 方法。

Startup 类的构造函数

构造函数,可以帮我们设置配置文件的位置,比如下面的代码设置了 appsettings.json 。

public Startup(IHostingEnvironment env){    // 设置 配置文件 的位置    var builder = new ConfigurationBuilder()        .AddJsonFile("appsettings.json")        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);    if (env.IsDevelopment())    {        // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709        builder.AddUserSecrets();    }    builder.AddEnvironmentVariables();    Configuration = builder.Build();}

默认的 appsettings.json 内容如下:

{  "Logging": {    "IncludeScopes": false,    "LogLevel": {      "Default": "Verbose",      "System": "Information",      "Microsoft": "Information"    }  }}

ConfigureServices 方法

ConfigureServices 用来定义我们使用了哪些服务,比如MVC、EF、Identity、Logging、Route;也可以自定义一些服务。 这里定义的服务是基于依赖注入(Dependency Injection)的。 在ASP.NET Core 1.0中,依赖注入技术的是被大量使用的。

下面的例子中,配置了EntityFramework(用于数据访问,需要在 appsettings.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 方法用于加载各种需要的中间件,类似于传统的 OWIN(Open Web Interface for .NET)。 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 中设置是无效的。

0 0