MVC4制作网站教程第二章 用户登陆2.2(2)

在项目里添加Extensions文件夹,添加一个类UserAuthorizeAttribute 继承自AuthorizeAttribute,重写AuthorizeCore方法用来实现用户是否已经登陆的验证,权限验证在写权限功能时在补充 

using Ninesky.Repository; namespace System.Web.Mvc { /// <summary> /// 用户权限验证 /// </summary> public class UserAuthorizeAttribute :AuthorizeAttribute { /// <summary> /// 核心【验证用户是否登陆】 /// </summary> /// <param></param> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { //检查Cookies["User"]是否存在 if (httpContext.Request.Cookies["User"] == null) return false; //验证用户名密码是否正确 HttpCookie _cookie = httpContext.Request.Cookies["User"]; string _userName = _cookie["UserName"]; string _password = _cookie["Password"]; httpContext.Response.Write("用户名:"+_userName); if (_userName == "" || _password == "") return false; UserRepository _userRsy = new UserRepository(); if (_userRsy.Authentication(_userName, _password) == 0) return true; else return false; } } }

以后只要在需要登陆后才能操作的Action或Controller上加[UserAuthorize]就可实现验证是否已经登录了。
退出功能,在UserController添加Logout Action 

/// <summary> /// 退出系统 /// </summary> /// <returns></returns> public ActionResult Logout() { if (Request.Cookies["User"] != null) { HttpCookie _cookie = Request.Cookies["User"]; _cookie.Expires = DateTime.Now.AddHours(-1); Response.Cookies.Add(_cookie); } Notice _n = new Notice { Title = "成功退出", Details = "您已经成功退出!", DwellTime = 5, NavigationName="网站首页", NavigationUrl = Url.Action("Index", "Home") }; return RedirectToAction("Notice", "Prompt", _n); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjydjp.html