ASP.NET MVC form驗證

來源:互聯網
上載者:User
網站結構

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到期時間長度. 但是如果new HttpCookie(FormsAuthentication.FormsCookieName, ticString) 這個cookie對象沒有設定到期時間, 那麼上面設定的時間長度再長, cookie的生命週期還是瀏覽器的生命週期.
public ActionResult Logout() {
            FormsAuthentication.SignOut();
            return Redirect(FormsAuthentication.LoginUrl);
        }

這樣, 在預設首頁 home/index 中可以得到

八卦一下. User的值是在哪裡獲得的呢?我們載入進來一個DLL, 自訂的httpmodulehttp://www.cnblogs.com/jianjialin/archive/2011/06/14/2080880.html

跟蹤一下. 發現在application_AuthenticateRequest事件裡面, 我們可以獲得User對象了.

代碼下載: 群共用搜尋 mvc安全驗證

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.