因为是转载文章 在此标明出处,以前有文章是转的没标明的请谅解,因为有些已经无法找到出处,或者与其它原因。
如有冒犯请联系本人,或删除,或标明出处。
因为好的文章,以前只想收藏,但连接有时候会失效,所以现在碰到好的直接转到自己这里。
原文 出处http://blog.csdn.net/hj458377603/article/details/9451603
1.asp.net mvc自带的权限表的创建是在InitializeSimpleMembershipAttribute.cs中实现的。
2.InitializeSimpleMembershipAttribute.cs
- using System;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Threading;
- using System.Web.Mvc;
- using WebMatrix.WebData;
- using FindU1.Models;
- namespace FindU1.Filters
- {
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
- public sealed class InitializeSimpleMembershipAttribute : 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<UserContext>(null);
- try
- {
- using (var context = new UserContext())
- {
- if (!context.Database.Exists())
- {
- // Create the SimpleMembership database without Entity Framework migration schema
- ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
- }
- }
- //Web.config中的配置,前四个参数分别是数据库连接ConnectionString,表名称,UserId,UserName(对应的数据库中的字段)
- WebSecurity.InitializeDatabaseConnection("UserContext", "Users", "UserID", "Email", 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);
- }
- }
- }
- }
- }
3.Web.Config中的数据库的配置
- <connectionStrings>
- <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-FindU1-20130720205848;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-FindU1-20130720205848.mdf"
- providerName="System.Data.SqlClient" />
- <add name="UserContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=UserContext-20130721150726; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|UserContext-20130721150726.mdf"
- providerName="System.Data.SqlClient" />
- </connectionStrings>
4.出现 未启用角色管理器功能。错误
此时需要修改配置文件,加上
- <compilation debug="true" targetFramework="4.5">
- <assemblies>
- <add assembly="WebMatrix.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
- <add assembly="WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
- </assemblies>
- </compilation>