学用MVC4做网站六后台管理:6.1管理员(续)

接6.1

首先在~/Areas/Admin/Models文件夹添加管理员模型Administrator.cs

using System.ComponentModel.DataAnnotations;

namespace Ninesky.Areas.Admin.Models
{
    /// <summary>
    /// 管理员模型
    /// </summary>
    public class Administrator
    {
        [Key]
        public int AdministratorId { get; set; }
        [Display(Name = "系统账号")]
        [Required(ErrorMessage = "×")]
        public bool IsPreset { get; set; }
        [Display(Name="用户名",Description="(必填) 4-20个字符。")]
        [Required(ErrorMessage="×")]
        [StringLength(20,MinimumLength=4,ErrorMessage="×")]
        public string AdminName { get; set; }
        [Display(Name = "密码", Description = "(必填) 6-20个字符。")]
        [Required(ErrorMessage = "×")]
        [StringLength(256, MinimumLength = 6, ErrorMessage = "×")]
        public string PassWord { get; set; }
        [Display(Name = "姓名", Description = "填写姓名可以更容易识别管理员。")]
        [StringLength(20, ErrorMessage = "×")]
        public string Name { get; set; }
        [Display(Name = "电子邮件", Description = "(必填) 不多于255个字符。")]
        [Required(ErrorMessage = "×")]
        [EmailAddress()]
        [StringLength(256, ErrorMessage = "×")]
        public string Email { get; set; }
    }
}

在~/Areas/Admin/Repository文件夹 添加接口IAdministrator(为的实现所谓的Repository模式)

接口中有管理员的添加、删除、修改、查找、验证等。基本上就这些差不多了。

using Ninesky.Areas.Admin.Models;
using System.Collections.Generic;

namespace Ninesky.Areas.Admin.Repository
{
    public interface IAdministrator
    {
        /// <summary>
        /// 添加管理员
        /// </summary>
        /// <param name="admin">管理员</param>
        /// <returns></returns>
        bool Add(Administrator admin);
        /// <summary>
        /// 更改管理员信息
        /// </summary>
        /// <param name="admin">管理员</param>
        bool Modify(Administrator admin);
        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="adminId">管理员Id</param>
        bool Delete(int adminId);
        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="admin">管理员</param>
        bool Delete(Administrator admin);
        /// <summary>
        /// 验证管理员账号、密码【返回值-1此管理员不存在,0密码错误,1验证通过】
        /// </summary>
        /// <param name="adminName">用户名</param>
        /// <param name="passWord">密码【加密】</param>
        int Authentication(string userName, string passWord);
        /// <summary>
        /// 查找管理员
        /// </summary>
        /// <param name="adminId">管理员Id</param>
        Administrator Find(int adminId);
        /// <summary>
        /// 查找管理员
        /// </summary>
        /// <param name="adminName">管理员名称</param>
        /// <returns></returns>
        Administrator Find(string adminName);
        /// <summary>
        /// 查找全部管理员
        /// </summary>
        List<Administrator> Find();
    }
}

再添加接口的实现类AdministratorRepository.cs

using Ninesky.Areas.Admin.Models;
using Ninesky.Repository;
using System.Collections.Generic;
using System.Linq;

namespace Ninesky.Areas.Admin.Repository
{
    public class AdministratorRepository:IAdministrator
    {
        private NineskyContext db;
        public bool Add(Administrator admin)
        {
            using (db = new NineskyContext())
            {
                if (db.Administrators.Any(a => a.AdminName == admin.AdminName)) return false;
                db.Administrators.Add(admin);
                return db.SaveChanges() > 0;
            }
            
        }
        public int Authentication(string adminName, string passWord)
        {
            using (db = new NineskyContext())
            {
                if (db.Administrators.Any(a => a.AdminName == adminName))
                {
                    var _admin = db.Administrators.SingleOrDefault(a => a.AdminName == adminName);
                    if (_admin.PassWord == passWord) return 1;
                    else return 0;
                }
                else return -1;
            }
        }
        public bool Delete(int adminId)
        {
            using (db = new NineskyContext())
            {
                db.Administrators.Remove(db.Administrators.SingleOrDefault(a => a.AdministratorId == adminId));
                return db.SaveChanges() > 0;
            }
        }
        public bool Delete(Administrator admin)
        {
            using (db = new NineskyContext())
            {
                db.Administrators.Remove(admin);
                return db.SaveChanges() > 0;
            }
        }
        public Administrator Find(int adminId)
        {
            using (db = new NineskyContext())
            {
                return db.Administrators.SingleOrDefault(a => a.AdministratorId == adminId);
            }
        }
        public Administrator Find(string adminName)
        {
            using (db = new NineskyContext())
            {
                return db.Administrators.SingleOrDefault(a => a.AdminName == adminName);
            }
        }
        public List<Administrator> Find()
        {
            using (db = new NineskyContext())
            {
                return db.Administrators.ToList();
            }
        }
        public bool Modify(Administrator admin)
        {
            using (db = new NineskyContext())
            {
                db.Administrators.Attach(admin);
                db.Entry<Administrator>(admin).State = System.Data.EntityState.Modified;
                return db.SaveChanges() > 0;
            }
        }
    }
}

在~/Areas/Admin/Controllers文件夹添加管理员控制器【AdministratorController】

using Ninesky.Areas.Admin.Extensions;
using Ninesky.Areas.Admin.Models;
using Ninesky.Areas.Admin.Repository;
using Ninesky.Models;
using System.Linq;
using System.Web.Mvc;

namespace Ninesky.Areas.Admin.Controllers
{
    public class AdministratorController : Controller
    {
        private IAdministrator adminRsy;
        public AdministratorController()
        {
            adminRsy = new AdministratorRepository();
        }
}
}

这里用Repository模式。其实就是先声明接口IAdministrator adminRsy,然后在初始化函数中具体实例化(new AdministratorRepository(); )。

为了方便使用,再写两个静态变量AdminName与AdminInfo。

AdminName—获取设置登录的管理员名称

AdminInfo—获取登录的管理员信息。

代码如下:

#region 静态属性
        /// <summary>
        /// 管理员登录名
        /// </summary>
        public static string AdminName
        {
            get
            {
                string _adminName = string.Empty;
                if (System.Web.HttpContext.Current.Session["AdminName"] != null) _adminName = System.Web.HttpContext.Current.Session["AdminName"].ToString();
                return _adminName;
            }
            set
            {
                if (string.IsNullOrEmpty(value)) System.Web.HttpContext.Current.Session.Remove("AdminName");
                else
                {
                    System.Web.HttpContext.Current.Session.Timeout = 60;
                    System.Web.HttpContext.Current.Session.Add("AdminName", value);
                }
            }
        }
        /// <summary>
        /// 管理员信息
        /// </summary>
        public static Administrator AdminInfo
        {
            get
            {
                AdministratorRepository _adminRsy = new AdministratorRepository();
                return _adminRsy.Find(AdministratorController.AdminName);
            }
        }
        #endregion
    }

再写一个管理员是否登录的Attribute。

这个比较简单,继承自AuthorizeAttribute。需要重写两个函数:

1、AuthorizeCore函数,通过检查AdminName属性是否为空,来判断管理员是否登录。

2、HandleUnauthorizedRequest函数,失败后跳转到的页面。

先在~/Areas/Admin/添加Extensions文件夹,然后在文件夹内添加类AdminAuthorizeAttribute.cs。内容如下:

using Ninesky.Areas.Admin.Controllers;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Ninesky.Areas.Admin.Extensions
{
    /// <summary>
    ///  管理员权限验证
    /// </summary>
    public class AdminAuthorizeAttribute:AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (string.IsNullOrEmpty(AdministratorController.AdminName)) return false;
            else return true;
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectToRouteResult("Admin_default", new RouteValueDictionary(new { controller = "Administrator", action = "Login" }));
        }
    }
}

 

到这差不多了,明天具体写Controller和view。 待续!

你可能感兴趣的:(mvc)