Microsoft.AspNet.Identity 3.0(一) 初始Identity结构

来源:互联网 发布:java导出excel合并行 编辑:程序博客网 时间:2024/05/22 10:47

在ASP.NET 5 中,微软的Identity已经升级到了3.0,很多代码已经基本上不一样了。


我们来看看有什么不一样




选择这个来创建应用之后,我们来看看结构。



Migrations里已经给我们创建好了Code First专用的迁移类

但却多了一个ApplicationDbContextModelSnapshot.cs   这是个什么东东?

这是在EntityFramework 7 为团队开发时,Code First迁移用的Context上下文所用的快照。

可以具体可以参考这里,只不过是全英文的,看视频我想会明白个大概吧。


接下来看Model里的ApplicationDbContext和ApplicationUser

来比较一下在OWIN中,这两个的不同


这个是OWIN中的代码片段

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>    {        public ApplicationDbContext()            : base("DefaultConnection", throwIfV1Schema: false)        {        }        public static ApplicationDbContext Create()        {            return new ApplicationDbContext();        }    }

    // 可以通过向 ApplicationUser 类添加更多属性来为用户添加配置文件数据。若要了解详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=317594。    public class ApplicationUser : IdentityUser    {        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)        {            // 请注意,authenticationType 必须与 CookieAuthenticationOptions.AuthenticationType 中定义的相应项匹配            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);            // 在此处添加自定义用户声明                        return userIdentity;        }    }

这里是ASP.NET 5的代码片段

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>    {        protected override void OnModelCreating(ModelBuilder builder)        {            base.OnModelCreating(builder);            // Customize the ASP.NET Identity model and override the defaults if needed.            // For example, you can rename the ASP.NET Identity table names and more.            // Add your customizations after calling base.OnModelCreating(builder);        }    }

    // Add profile data for application users by adding properties to the ApplicationUser class    public class ApplicationUser : IdentityUser    {    }

少了很多代码


View里的代码就不说了,那是MVC6的内容。

主要是再看看Startup.cs里的代码

public class Startup    {        public Startup(IHostingEnvironment env)        {            // Set up configuration sources.            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();        }        public IConfigurationRoot Configuration { get; set; }        // This method gets called by the runtime. Use this method to add services to the container.        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>();        }        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            loggerFactory.AddConsole(Configuration.GetSection("Logging"));            loggerFactory.AddDebug();            if (env.IsDevelopment())            {                app.UseBrowserLink();                app.UseDeveloperExceptionPage();                app.UseDatabaseErrorPage();            }            else            {                app.UseExceptionHandler("/Home/Error");                // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859                try                {                    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()                        .CreateScope())                    {                        serviceScope.ServiceProvider.GetService<ApplicationDbContext>()                             .Database.Migrate();                    }//这里添加了配置                }                catch { }            }            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());            app.UseStaticFiles();            app.UseIdentity();//这里添加了配置            // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715            app.UseMvc(routes =>            {                routes.MapRoute(                    name: "default",                    template: "{controller=Home}/{action=Index}/{id?}");            });        }        // Entry point for the application.        public static void Main(string[] args) => WebApplication.Run<Startup>(args);    }

这就涉及到了很多关于ASP.NET5的知识,建议先去学习下ASP.NET5的基本知识比较好


这是配置使用的数据库和数据库连接字符串

            // Add framework services.            services.AddEntityFramework()                .AddSqlServer()                .AddDbContext<ApplicationDbContext>(options =>                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));


配置使用的实体类型,其实就相当于对ApplicationDbContext的依赖注入

            services.AddIdentity<ApplicationUser, IdentityRole>()                .AddEntityFrameworkStores<ApplicationDbContext>()                .AddDefaultTokenProviders();


应用使用Identity中间件功能
app.UseIdentity();



主要是这三段代码,下一张来说说如何修改注册时的验证配置,看看跟我们的v2有多少的不一样。

1 0
原创粉丝点击