2011-01-27 51 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(); 
    } 
}