網站結構
webconfig
設置為form驗證, 並拒絕所有的匿名用戶<authentication mode="Forms"><forms loginUrl="~/Account/Index" timeout="2880" path="/" /></authentication><authorization><deny users="?"/></authorization>
如果我們徐凱開放首頁比如說Home/Index,那么做如下配置. 如果是Home文件夾下所有的頁面都能訪問, 那么 path=”Home”即可
<location path="Home/Index"><system.web><authorization><allow users="*" /></authorization></system.web></location>
cookie
啟動程序, 來到登錄頁面. 如果登錄成功, 那么我們需要寫入cookie.
登陸頁面
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<mvc安全驗證.Models.User>" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"><title>Index</title></head><body><div><% using( Html.BeginForm()){%>登錄<%: Html.TextBoxFor(m => m.UserName, new { @class = "log" })%><%: Html.TextBoxFor(x => x.RealName) %><br /><input type="submit" value="login" /><%};%></div></body></html>處理方法[HttpPost]public ActionResult Index(Models.User model) {if (model.UserName == "admin"){//創造票據FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(model.UserName, false, 1);//加密票據string ticString = FormsAuthentication.Encrypt(ticket);//輸出到客戶端Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, ticString));//跳轉到登錄前頁面return Redirect(HttpUtility.UrlDecode( Request.QueryString["ReturnUrl"]));}return View();}退出.通過 new FormsAuthenticationTicket(model.UserName, false, 時長); 設置.AXPXAUTH過期時長. 但是如果 newHttpCookie(FormsAuthentication.FormsCookieName, ticString) 這個cookie對象沒有設置過期時間, 那么上面設置的時長再長, cookie的生命周期還是瀏覽器的生命周期.public ActionResult Logout() {FormsAuthentication.SignOut();return Redirect(FormsAuthentication.LoginUrl);}
八卦一下. User的值是在哪里獲得的呢?我們加載進來一個DLL, 自定義的httpmodulehttp://www.cnblogs.com/jianjialin/archive/2011/06/14/2080880.html
跟蹤一下. 發現在application_AuthenticateRequest事件里面, 我們可以獲得User對象了.


