編號:ylbtechASPnetMvcSecurity100010010
1,功能描述 |
ASP.net MVC下利用 System.Web.Security.FormsAuthentication類,驗證用戶的狀態(匿名|已登錄 )
以項目為例:在視圖和和區域里的視圖,分別都列舉倆個頁面(允許匿名和不允許匿名)。
2,技術與環 境 |
ASP.net MVC下System.Web.Security.FormsAuthentication類,驗證用戶的狀 態(匿名|已登錄)
3,數據庫設 計 |
無
4,功能截圖 |
4.1,匿名狀態下()
4.1.1 /Home/Index 網站首頁
4.1.2 /Account/Login 登錄
4.1.3 只要是匿名用戶,單擊加“[NM]”修飾的地址,都會跳轉到/Accout/Login頁面
4.2,已登錄狀態下
4.2.1 /Accout/Index 用戶中心
5,代碼分析 |
5.1, /web.config 設置重定向登錄頁面
<authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication>
5.2, /Controllers/AccountController.cs 賬戶管理控制器 ylb_tip:加“[Authorize]”修飾的方法拒絕匿名。
using System.Web.Mvc; using System.Web.Security; namespace MvcSecurity.Controllers { public class AccountController : Controller { // // GET: /Account/ [Authorize] public ActionResult Index() { return View(); } // // GET: /Account/Login [HttpGet] public ActionResult Login() { // 如果是登錄狀態,則條轉到個人主頁 if (Session["Username"] != null) { return RedirectToAction("Index"); } else { return View(); } } // // Post: /Account/Login [HttpPost] public ActionResult Login(string username,string userpass) { if (username == "sunshine" && userpass == "m123") { //創建身份驗證票證,即轉換為“已登錄狀態” FormsAuthentication.SetAuthCookie(username, false); //存入Session Session["Username"] = username; //如果是跳轉過來的,則返回上一頁面 if (!string.IsNullOrEmpty(Request["ReturnUrl"])) { string returnUrl = Request["ReturnUrl"]; return Redirect(returnUrl); } else { //用戶個人主頁 return RedirectToAction("Index"); } } else { ViewData["Tip"] = "用戶名或密碼有誤!"; return View(); } } // // GET: /Account/Logout [HttpGet] public ActionResult Logout() { //取消Session會話 Session.Abandon(); //刪除Forms驗證票證 FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } } }
5.3 /Controllers/HomeController.cs 首頁控制器(注:區域里面的權限原理相同,在這兒就不多介紹)
using System.Web.Mvc; namespace MvcSecurity.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } // // GET: /Home/VipIndex [Authorize] public ActionResult VipIndex() { return View(); } } }
6,示例 |講解案例下載 |
博客園講解: http://ylbtech.cnblogs.com/
百度文庫開發文檔: http://passport.baidu.com/? business&aid=6&un=ylbtech#7
谷歌開源代碼下載: http://code.google.com/p/ylbtechaspnetmvc/downloads/list
請單擊 “ylbtechASPnetMvcSecurity100010010”
百度網盤 http://pan.baidu.com/s/1i49zn73
請單擊 “ASPnetMvcSecurity100010010”
![]() |
作者:ylbtech 出處:http://ylbtech.cnblogs.com/ 本文版權歸作者和博客園共有,歡迎轉載,但未經作 者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究 法律責任的權利。 |
最終目標 |
“代碼的國際化標准 示例 ylb,tech”,最大程度地規范軟件編程 開發統一,優質, 高效,易學,為建設軟件強國(中國)而努 力。