zoukankan      html  css  js  c++  java
  • ASP.NET Core 1.0 入门——Application Startup

    ASP.NET Core 1.0 入门——Application Startup

    警告

    您当前查看的页面是未经授权的转载!
    如果当前版本排版错误,请前往查看最新版本:http://www.cnblogs.com/qin-nz/p/aspnet5-application-startup.html

    提示

    更新时间: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 的参数,也可以包含一些其他的五福 IHostingEnvironmentILoggerFactory 的参数。

    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 官方文档

    声明 知识共享许可协议

    ASP.NET Core 1.0 入门——Application Startup勤奋的小孩 创作,采用 知识共享 署名-相同方式共享 4.0 国际 许可协议进行许可。
    本许可协议授权之外的使用权限可以从 http://space.cnblogs.com/msg/send/qin-nz 处获得。

  • 相关阅读:
    QEMU KVM Libvirt手册(10):Managing Virtual Machines with libvirt
    Openssl的证书操作
    QEMU KVM Libvirt手册(10): KVM的各种限制
    QEMU KVM Libvirt手册(9): network
    nginx调优(一)
    Apache调优(二)
    Apache调优(一)
    使用Varnish为网站加速
    Linux系统调优——系统整体运行状态排查(六)
    Linux系统调优——内核相关参数(五)
  • 原文地址:https://www.cnblogs.com/qin-nz/p/aspnet5-application-startup.html
Copyright © 2011-2022 走看看