Simplemembership是Dotnet MVC4工程内置的权限管理模块,本系列文章主要是关于使用Simplemembership如何实现可配置的用户权限管理。
首先我们新建一个MVC4工程:
我们看一下新建的工程目录,和Simplemembership有关系的内容主要在InitializeSimpleMembershipAttribute.cs和AccountModels.cs这两个文件里。
我们来看一下InitializeSimpleMembershipAttribute.cs。这里我们主要看的是数据库的创建和加载。至于MVC4内部对SimpleMembership的实现,高人可以去研究一下。本教程不作介绍。
- using System;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Threading;
- using System.Web.Mvc;
- using System.Web;
- using WebMatrix.WebData;
- namespace TYStudio
- {
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
- public sealed class InitializeSimpleMembership : ActionFilterAttribute
- {
- private static SimpleMembershipInitializer _initializer;
- private static object _initializerLock = new object();
- private static bool _isInitialized;
- public override void OnActionExecuting(ActionExecutingContext filterContext)
- {
- // Ensure ASP.NET Simple Membership is initialized only once per app start
- LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
- }
- private class SimpleMembershipInitializer
- {
- public SimpleMembershipInitializer()
- {
- Database.SetInitializer<TYStudioMembershipContext>(null);
- try
- {
- using (var context = new TYStudioMembershipContext())
- {
- if (!context.Database.Exists())
- {
- // Create the SimpleMembership database without Entity Framework migration schema
- ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
- }
- }
- WebSecurity.InitializeDatabaseConnection("TYStudioUsersConnectionString", "UserProfile", "UserId", "UserName", autoCreateTables: true);
- }
- catch (Exception ex)
- {
- throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
- }
- }
- }
- }
- }
AccountModels.cs里面是用户管理页面的一些基本的ViewModel,一个UsersContext和UserProfile表的Model映射。以后我们可以通过修改这个文件进行实例化自己的Membership数据库结构。
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Data.Entity;
- using System.Globalization;
- using System.Web.Security;
- namespace TYStudioSimplemembership.Models
- {
- public class UsersContext : DbContext
- {
- public UsersContext()
- : base("DefaultConnection")
- {
- }
- public DbSet<UserProfile> UserProfiles { get; set; }
- }
- [Table("UserProfile")]
- public class UserProfile
- {
- [Key]
- [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
- public int UserId { get; set; }
- public string UserName { get; set; }
- }
- public class RegisterExternalLoginModel
- {
- [Required]
- [Display(Name = "User name")]
- public string UserName { get; set; }
- public string ExternalLoginData { get; set; }
- }
- public class LocalPasswordModel
- {
- [Required]
- [DataType(DataType.Password)]
- [Display(Name = "Current password")]
- public string OldPassword { get; set; }
- [Required]
- [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
- [DataType(DataType.Password)]
- [Display(Name = "New password")]
- public string NewPassword { get; set; }
- [DataType(DataType.Password)]
- [Display(Name = "Confirm new password")]
- [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
- public string ConfirmPassword { get; set; }
- }
- public class LoginModel
- {
- [Required]
- [Display(Name = "User name")]
- public string UserName { get; set; }
- [Required]
- [DataType(DataType.Password)]
- [Display(Name = "Password")]
- public string Password { get; set; }
- [Display(Name = "Remember me?")]
- public bool RememberMe { get; set; }
- }
- public class RegisterModel
- {
- [Required]
- [Display(Name = "User name")]
- public string UserName { get; set; }
- [Required]
- [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
- [DataType(DataType.Password)]
- [Display(Name = "Password")]
- public string Password { get; set; }
- [DataType(DataType.Password)]
- [Display(Name = "Confirm password")]
- [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
- public string ConfirmPassword { get; set; }
- }
- public class ExternalLogin
- {
- public string Provider { get; set; }
- public string ProviderDisplayName { get; set; }
- public string ProviderUserId { get; set; }
- }
- }
InitializeSimpleMembershipAttribute.cs和AccountModels.cs用到了Entityfamework codefirst,本教程不做详细介绍,可以去网上搜索相关技术文章。
在运行工程前,我们需要修改一下Web.Config文件的默认连接串DefaultConnection指到我们自己的数据库,填好想要的数据库名称例如SmpleMembershipDB,保存后就可以运行工程。使用Simplemembership,我们看到Web.config文件中并没有对membership的太多的配置只有一个连接串和一个没有登录的返回页面这两个信息,新的Simplemembership的配置不像以前需要在web.confg中配置prodiver,已经集成在了MVC4里面,简化了配置。
第一次编译运行工程成功会看到默认的Home Page,这时点击右上角的Register按钮我们就可以注册用户了,系统会根据DefaultConnection自动创建Membership的数据库如下图。
这里有一个问题,有些人可能上来没有修改DefaultConnection,就运行了程序注册了用户,这样也是可以的,系统会用Visual Studio 2010 安装的Sqlserver Express版本创建Membership数据库到工程的App_Data目录下,你会看到一串的数据库名称MDF文件。但是这显然不是我们想要的。
系统默认创建的UserProfile表十分简单只有UserId和UserName两个字段,更具具体的需求我们需要像这个表中添加新的字段,如Email、地址等信息。这个会在下篇文章中分享给大家。
您好,本人是Simplemembership初学者!我按照(Simplemembership实现用户权限管理-初步认识)的步骤,新建了MVC4 Internat 应用程序,但是连接上数据库后却没办法自动生成UserProfile等上述的5个表,请问这是哪里出了问题,有该如何解决!所有步骤都正确,唯独不可以生成表