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 处获得。

  • 相关阅读:
    利用相关的Aware接口
    java 值传递和引用传递。
    权限控制框架Spring Security 和Shiro 的总结
    优秀代码养成
    Servlet 基础知识
    leetcode 501. Find Mode in Binary Search Tree
    leetcode 530. Minimum Absolute Difference in BST
    leetcode 543. Diameter of Binary Tree
    leetcode 551. Student Attendance Record I
    leetcode 563. Binary Tree Tilt
  • 原文地址:https://www.cnblogs.com/qin-nz/p/aspnet5-application-startup.html
Copyright © 2011-2022 走看看