asp.net里面的身份驗證和授權(2)_.Net教程

      編輯Tag賺U幣
      教程Tag:暫無Tag,歡迎添加,賺取U幣!

      推薦:ASP.NET的高級調試技巧
        對于一個項目來說,你不可能通過設定起始頁按F5鍵進行調試,原因是:各個網頁間的關聯性太強,要驗證的的東西也很多。在調試時很難進行(實際上在我做的項目中根本不能進行)。   那么

      login.aspx.cs代碼如下

      private void btnLoginBetter_Click(object sender, System.EventArgs e)
      {
      if (this.tbName.Text == "admin" && this.tbPass.Text == "admin")
      {
      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,this.tbName.Text,DateTime.Now,DateTime.Now.AddMinutes(30),this.PersistCookie.Checked,"User");
      //創建一個驗證票據

      string cookieStr = FormsAuthentication.Encrypt(ticket);
      //進行加密

      HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,cookieStr);
      //創建一個cookie,cookie名為web.config設置的名,值為加密后的數據cookieStr,

      if (this.PersistCookie.Checked)//判斷用戶是否選中保存cookie

      cookie.Expires = ticket.Expiration;//獲取cookie過期時間

      cookie.Path = FormsAuthentication.FormsCookiePath;//設置cookie保存路徑

      Response.Cookies.Add(cookie);
      string strRedirect;
      strRedirect = Request["ReturnUrl"];//取出返回url

      if (strRedirect == null)
      strRedirect = "Default.aspx";
      Response.Redirect(strRedirect,true);

      }
      else
      {
      Response.Write("<script>alert('帳號或密碼錯誤!');self.location.href='02login.aspx'</script>");
      }
      }

      Default.aspx HTML代碼

      <body MS_POSITIONING="GridLayout">
      <form id="Form1" method="post" runat="server">
      <FONT face="宋體">
      <asp:Label id="Label1" style="Z-INDEX: 106; LEFT: 224px; POSITION: absolute; TOP: 72px" runat="server">用戶名稱:</asp:Label>
      <asp:Label id="Label2" style="Z-INDEX: 102; LEFT: 220px; POSITION: absolute; TOP: 136px" runat="server">身份:</asp:Label>
      <asp:Label id="lbUser" style="Z-INDEX: 103; LEFT: 350px; POSITION: absolute; TOP: 79px" runat="server"></asp:Label>
      <asp:Label id="lbSf" style="Z-INDEX: 104; LEFT: 355px; POSITION: absolute; TOP: 133px" runat="server"></asp:Label>
      <asp:Button id="btnLogout" style="Z-INDEX: 105; LEFT: 261px; POSITION: absolute; TOP: 192px"
      runat="server" Text="注銷" Width="101px"></asp:Button></FONT>
      </form>
      </body>
      后置代碼

      private void Page_Load(object sender, System.EventArgs e)
      {
      this.lbUser.Text = User.Identity.Name;
      if (User.IsInRole("Admin"))
      this.lbSf.Text = "Admin";
      else
      this.lbSf.Text = "User";
      }

      分享:結合JavaScript與ASP.NET Web窗體進行程序開發
      ASP.NET為Web程序開發提供了新的范例。其中包括一系列基于服務器的控件,這些控件類似于HTML窗體中諸如文本框、按鈕等元素。使用這些控件的問題是必須調用服務器。JavaScript為很多任務提供多種

      來源:模板無憂//所屬分類:.Net教程/更新時間:2008-08-22
      相關.Net教程