2011-01-27 48 views
0

我從來沒有真正實現過註冊/登錄系統,所以我正在努力讓自己在C#/ ASP.NET(不使用ASP.NET的內置會員提供商)。我有點不清楚的是如何利用會話/ cookie來保持用戶在會話期間和會話之間登錄。如何正確實現會話的用戶系統

protected void Login_User(object sender, EventArgs e) 
{ 
    string username = usernameField.Text; 
    string password = passwordField.Text; 
    User user = UserRepository.FindUser(username); 
    if (user != null) 
    { 
     if (user.Password.Equals(Hash(password))) 
     { 
      // How do I properly login the user and keep track of his session? 
     } 
     else 
      Response.Write("Wrong password!"); 
    } 
    else 
     Response.Write("User does not exist!"); 
} 
+1

希望這不會用於生產代碼? – BrokenGlass 2011-01-27 16:30:15

+0

這當然是爲了學習的目的。 – 2011-01-27 16:30:39

回答

0

控制其正確的登錄系統相當複雜。

  1. 創建繼承System.Security.Principal.IPrincipal
  2. 另一類inherrit System.Security.Principal.IIdentity
  3. 分配的IPrincipal衍生物System.Web.HttpConext.Current.User
  4. 類如果你不想使用cookies,那麼把你的IPrincipal放到會話中。
  5. 如果HttpContext.Current.User丟失,然後通過從會話獲取重新分配(在第一次事件,例如page_init)。我的代碼,我在事件中使用的FormsAuthenticationTicket作爲cookie並重新分配在Global.asax中PostAuthenticateRequest

使用HttpContext.Current.User是ü可以標記法屬性的好事。

[Authorize] // authorized user only 
public void btn_click(...){...} 

我不知道正常的asp.net,但它在ASP MVC

和工作得很好,如果ü要使用cookie,嘗試System.Web.Securitiy.FormsAuthenticationTicket FormsAuthentication

樣品

public class WebUser:System.Security.Principal.IPrincipal 
{ 
    ... 
    public System.Security.Principal.IIdentity Identity{get; private set;} 
    public WebUser(...) 
    { 
    this.Identity = new WebIdentity(...); 
    HttpContext.Current.User = this; 
    } 
} 
public class WebIdentity : System.Security.Principal.IIdentity 
{ 
    ... 
} 

public void Login(...) 
{ 
    var newUser = new WebUser(...); 
} 
0

使用此:

public class FormsAuthenticationService 
{ 
    public void SignIn(string userName, bool createPersistentCookie) 
    { 
     if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName"); 

     FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); 
    } 

    public void SignOut() 
    { 
     FormsAuthentication.SignOut(); 
    } 
}