上次业务逻辑和展示层的架构都写了,可以开始进行具体功能的实现,这次先实现管理员的登录、验证和注销功能。
目录
MVC5 网站开发之六 管理员 2、添加、删除、重置密码、修改密码、列表浏览
一、业务逻辑层
1、实现256散列加密方法。
Ninesky.Core【右键】-> 添加->文件夹,输入文件夹名General。
General文件夹【右键】->添加->类,输入类名Security。
引用System.Security.Cryptography命名空间(1),并实现SHA256静态加密方法。
2、Administrator模型类
Ninesky.Core【右键】-> 添加->类,输入类名Administrator。
添加引用System.ComponentModel.DataAnnotations; 完成的类代码
using System; using System.ComponentModel.DataAnnotations; namespace Ninesky.Core { /// <summary> /// 管理员模型 /// </summary> public class Administrator { [Key] public int AdministratorID { get; set; } /// <summary> /// 帐号 /// </summary> [Required(ErrorMessage = "必须输入{0}")] [StringLength(30, MinimumLength = 4, ErrorMessage ="{0}长度为{2}-{1}个字符")] [Display(Name ="帐号")] public string Accounts { get; set; } /// <summary> /// 密码 /// </summary>
[DataType(DataType.Password)] [Required(ErrorMessage = "必须输入{0}")] [StringLength(256,ErrorMessage = "{0}长度少于{1}个字符")] [Display(Name = "密码")] public string Password { get; set; } /// <summary> /// 登录IP /// </summary> [Display(Name = "登录IP")] public string LoginIP { get; set; } /// <summary> /// 登录时间 /// </summary> [Display(Name = "登录时间")] public Nullable<DateTime> LoginTime { get; set; } /// <summary> /// 创建时间 /// </summary> [Display(Name = "创建时间")] public DateTime CreateTime { get; set; } } }
3、数据上下文
打开Ninesky.Core->NineskyContext.cs 添加Administrators属性
红框内为添加内容。
4、AdministratorManager管理类
Ninesky.Core【右键】-> 添加->类,输入类名AdministratorManager。
类继承自BaseManager<Administrator>。
为类添加Ninesky.Core.Types引用。
using Ninesky.Core.Types; using System; namespace Ninesky.Core { public class AdministratorManager : BaseManager<Administrator> { /// <summary> /// 添加 /// </summary> /// <param name="admin">管理员实体</param> /// <returns></returns> public override Response Add(Administrator admin) { Response _resp = new Response(); if (HasAccounts(admin.Accounts)) { _resp.Code = 0; _resp.Message = "帐号已存在"; } else _resp = base.Add(admin); return _resp; } /// <summary> /// 修改密码 /// </summary> /// <param name="administratorID">主键</param> /// <param name="password">新密码【密文】</param> /// <returns></returns> public Response ChangePassword(int administratorID, string password) { Response _resp = new Response(); var _admin = Find(administratorID); if (_admin == null) { _resp.Code = 0; _resp.Message = "该主键的管理员不存在"; } else { _admin.Password = password; _resp = Update(_admin); } return _resp; } /// <summary> /// 删除 /// </summary> /// <param name="administratorID">主键</param> /// <returns></returns> public override Response Delete(int administratorID) { Response _resp = new Response(); if (Count() == 1) { _resp.Code = 0; _resp.Message = "不能删除唯一的管理员帐号"; } else _resp = base.Delete(administratorID); return _resp; } /// <summary> /// 查找 /// </summary> /// <param name="accounts">帐号</param> /// <returns></returns> public Administrator Find(string accounts) { return base.Repository.Find(a => a.Accounts == accounts); } /// <summary> /// 帐号是否存在 /// </summary> /// <param name="accounts">帐号</param> /// <returns></returns> public bool HasAccounts(string accounts) { return base.Repository.IsContains(a => a.Accounts.ToUpper() == accounts.ToUpper()); } /// <summary> /// 更新登录信息 /// </summary> /// <param name="administratorID">主键</param> /// <param name="ip">IP地址</param> /// <param name="time">时间</param> /// <returns></returns> public Response UpadateLoginInfo(int administratorID, string ip, DateTime time) { Response _resp = new Response(); var _admin = Find(administratorID); if (_admin == null) { _resp.Code = 0; _resp.Message = "该主键的管理员不存在"; } else { _admin.LoginIP = ip; _admin.LoginTime = time; _resp = Update(_admin); } return _resp; } /// <summary> /// 验证 /// </summary> /// <param name="accounts">帐号</param> /// <param name="password">密码【密文】</param> /// <returns>Code:1-成功;2-帐号不存在;3-密码错误</returns> public Response Verify(string accounts, string password) { Response _resp = new Response(); var _admin = base.Repository.Find(a => a.Accounts == accounts); if (_admin == null) { _resp.Code = 2; _resp.Message = "帐号为:【" + accounts + "】的管理员不存在"; } else if (_admin.Password == password) { _resp.Code = 1; _resp.Message = "验证通过"; } else { _resp.Code = 3; _resp.Message = "帐号密码错误"; } return _resp; } } }
二、展示层实现
首先,添加css。
Ninesky.Web->Content【右键】->添加->试样表,输入名称StyleControl。
打开Ninesky.Web->App_Start->BundleConfig.cs。
添加红框内代码。StyleControl.css具体内容这里省略了。
其次,添加对Ninesky.Core的引用。
Ninesky.Web->引用【右键】->添加引用.。在引用管理器中选择 项目->解决方案->Ninesky.Core.
处理完这两项内容就继续具体内容了:
1、管理员身份验证类AdminAuthorizeAttribute
AdminAuthorizeAttribute继承自AuthorizeAttribute,重写AuthorizeCore方法,通过Session["AdminID"]来判断管理员是否已经登录,重写HandleUnauthorizedRequest方法来处理未登录时的页面跳转。
using System.Web; using System.Web.Mvc; namespace Ninesky.Web.Areas.Control { /// <summary> /// 管理员身份验证类 /// </summary> public class AdminAuthorizeAttribute : AuthorizeAttribute { /// <summary> /// 重写自定义授权检查 /// </summary> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext.Session["AdminID"] == null) return false; else return true; } /// <summary> /// 重写未授权的 HTTP 请求处理 /// </summary> protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new RedirectResult("~/Control/Admin/Login"); } } }
Ninesky.Web->Areas->Control【右键】->添加->类,输入控制器名称HomeController。
为HomeController添加[AdminAuthorize]
2、管理员控制器
Ninesky.Web->Areas->Control->Controllers【右键】->添加->控制器。选择 MVC5 控制器 – 空, 输入控制器名称Admin。
在控制器中引用Ninesky.Core、Ninesky.Core.General和Ninesky.Web.Areas.Control.Models命名空间。
添加私有变量private AdministratorManager adminManager = new AdministratorManager();
为AdminController添加[AdminAuthorize]
3.1 管理员登录
3.1.1 登录视图模型
Ninesky.Web->Areas->Control->Models【右键】->添加->类,输入类名LoginViewModel。
namespace Ninesky.Web.Areas.Control.Models { /// <summary> /// 登录模型 /// </summary> public class LoginViewModel { /// <summary> /// 帐号 /// </summary> [Required(ErrorMessage = "必须输入{0}")] [StringLength(30, MinimumLength = 4, ErrorMessage = "{0}长度为{2}-{1}个字符")] [Display(Name = "帐号")] public string Accounts { get; set; } /// <summary> /// 密码 /// </summary> [DataType(DataType.Password)] [Required(ErrorMessage = "必须输入{0}")] [StringLength(20,MinimumLength =6, ErrorMessage = "{0}长度{2}-{1}个字符")] [Display(Name = "密码")] public string Password { get; set; } } }
3.1.2 登录方法
在AdminController中添加Login()方法
/// <summary> /// 登录 /// </summary> /// <returns></returns> [AllowAnonymous] public ActionResult Login() { return View(); }
3.1.3 登录视图
在Login()方法上点【右键】->添加视图
模板选Create,模型类选LoginViewModel ,选项选中引用脚本库。完成后代码
@model Ninesky.Web.Areas.Control.Models.LoginViewModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>登录</title> @Styles.Render("~/Content/controlcss") @Scripts.Render("~/bundles/modernizr") </head> <body> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") <div class="loginform"> <div class="form-horizontal"> <h2 class="text-primary">登录</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group form-group-lg"> @Html.EditorFor(model => model.Accounts, new { htmlAttributes = new { @class = "form-control", placeholder = "帐号" } }) @Html.ValidationMessageFor(model => model.Accounts, "", new { @class = "text-danger" }) </div> <div class="form-group form-group-lg"> @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", placeholder = "密码" } }) @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" }) </div> <div class="form-group form-group-lg"> <input type="submit" value="登录" class="btn btn-default pull-right" /> </div> } </div> </div> </body> </html>
在AdminController中添加登录的处理方法public ActionResult Login(LoginViewModel loginViewModel)
[AllowAnonymous] [ValidateAntiForgeryToken] [HttpPost] public ActionResult Login(LoginViewModel loginViewModel) { if(ModelState.IsValid) { string _passowrd = Security.SHA256(loginViewModel.Password); var _response = adminManager.Verify(loginViewModel.Accounts, _passowrd); if (_response.Code == 1) { var _admin = adminManager.Find(loginViewModel.Accounts); Session.Add("AdminID", _admin.AdministratorID); Session.Add("Accounts", _admin.Accounts); _admin.LoginTime = DateTime.Now; _admin.LoginIP = Request.UserHostAddress; adminManager.Update(_admin); return RedirectToAction("Index", "Home"); } else if (_response.Code == 2) ModelState.AddModelError("Accounts", _response.Message); else if (_response.Code == 3) ModelState.AddModelError("Password", _response.Message); else ModelState.AddModelError("",_response.Message); } return View(loginViewModel); }
4、注销
在AdminController中添加注销的处理方法public ActionResult Logout()
/// <summary> /// 注销 /// </summary> /// <returns></returns> public ActionResult Logout() { Session.Clear(); return RedirectToAction("Login"); }
完工可以按F5测试了。
登录界面,输入帐号mzwhj 密码123456,登录成功。
登录成功界面。
=====================================================
代码见:https://ninesky.codeplex.com/SourceControl/latest
代码下载:https://ninesky.codeplex.com 点击SOURCE CODE 点击Download下载源文件。