ASP.NET MVC4笔记(一) 扩展Simplemembership

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System.Web.Mvc;
namespace MvcClassManageSystem.ActionFilters
{
    public class LogStateFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            //string controller = filterContext.RouteData.Values["controller"].ToString();
            //string action = filterContext.RouteData.Values["action"].ToString();
            //System.Diagnostics.Debug.WriteLine("OnAction:" + controller + "/" + action);
            if (WebMatrix.WebData.WebSecurity.IsAuthenticated == true)
            {
                filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { Controller = "Home", action = "Index" }));
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static class WebUtility
    {
        private static SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;
        public static void CreateUserAndAccount(UserProfile userProfile, string Password)
        {
            WebSecurity.CreateUserAndAccount(userProfile.UserName, Password, new
            {
                //TO DO 数据库/模型更改之后别忘记修改此处!!!
                ClassId = userProfile.ClassId,
                UserExtraInfo_Phone = userProfile.UserExtraInfo.Phone,
                UserExtraInfo_Gender = userProfile.UserExtraInfo.Gender,
                UserExtraInfo_BirthDay = userProfile.UserExtraInfo.BirthDay,
                UserExtraInfo_UserDesc = userProfile.UserExtraInfo.UserDesc
            });
        }
        public static void DeleteUserAndAccount(string UserName)
        {
            membership.DeleteAccount(UserName);
            Roles.RemoveUserFromRoles(UserName, Roles.GetRolesForUser(UserName));
            membership.DeleteUser(UserName, true);
        }
        public static void ResetPassword(string UserName, string NewPassword)
        {
            WebSecurity.ResetPassword(WebSecurity.GeneratePasswordResetToken(UserName, 1), NewPassword);
        }
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Web.Mvc;
namespace MvcClassManageSystem.Filters
{
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("/Account/AccessError");
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System.Data.Entity;
using System.Linq;
using System.Web.Security;
using WebMatrix.WebData;
namespace MvcClassManageSystem.Models
{
    public class InitSecurityDb : DropCreateDatabaseAlways<DBManager>
    {
        protected override void Seed(DBManager context)
        {
            WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
            var roles = (SimpleRoleProvider)Roles.Provider;
 
            string[] RolesList = new string[] { "Admin", "Teacher", "Student" };
            foreach (var item in RolesList)
            {
                if (!roles.RoleExists(item))
                {
                    roles.CreateRole(item);
                }
            }
            //设置初始班级
            int ClassIndex = 0;
            using (var db = new DBManager())
            {
                var ret = db.ClassProfiles.SingleOrDefault(m => m.ClassName.CompareTo("未知班级") == 0);
                if (ret == null)
                {
                    ret = db.ClassProfiles.Add(new ClassProfile
                    {
                        ClassName = "未知班级",
                        Desc = "班级未知或无意义"
                    });
                    db.SaveChanges();
                }
                ClassIndex = ret.ClassId;
            }
            if (!WebSecurity.UserExists("管理员"))
            {
                WebUtility.CreateUserAndAccount(new UserProfile()
                {
                    UserName = "管理员",
                    ClassId = ClassIndex,
                    UserExtraInfo = new UserExtraInfo()
                    {
                        Phone = "18267912632",
                        Gender = MvcClassManageSystem.Models.Gender.男,
                        BirthDay = new System.DateTime(1993, 9, 28),
                        UserDesc = "本站的管理员!"
                    }
                }, "admin");
                System.Web.Security.Roles.AddUserToRole("管理员", "Admin");
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 protected void Application_Start()
        {
            Database.SetInitializer<DBManager>(new InitSecurityDb());
            DBManager db = new DBManager();
            db.Database.Initialize(true);
            if (!WebSecurity.Initialized)
            {
                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
            }
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }