C# 如何正确实现会话的用户系统

C# 如何正确实现会话的用户系统,c#,asp.net,session,membership,C#,Asp.net,Session,Membership,我以前从未真正实现过注册/登录系统,因此我正在尝试在C/ASP.NET中创建自己的系统,而不是使用ASP.NET的内置成员资格提供程序。我有点不清楚的是如何利用会话/cookie在会话期间和会话之间让用户登录 protected void Login_User(object sender, EventArgs e) { string username = usernameField.Text; string password = passwordField.Text; U

我以前从未真正实现过注册/登录系统,因此我正在尝试在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!");
}

您可以使用重定向到用户请求但由于身份验证而无法访问的页面,或者如果您想保持对用户重定向到的位置的控制,您可以使用

这对于正确的登录系统来说相当复杂

创建继承System.Security.Principal.IPrincipal的类 另一个固有的类System.Security.Principal.IIdentity 将IPrincipal导数分配给System.Web.HttpConext.Current.User 如果你不想使用cookies,那么将你的IPrincipal放入会话。 如果HttpContext.Current.User丢失,则在第一个事件(如page_init)中通过get from session重新分配。对于我的代码,我使用FormsAuthenticationTicket作为cookie,并在事件PostAuthenticateRequest上重新分配到Global.asax 使用HttpContext.Current.User的好处是可以标记方法属性

[Authorize] // authorized user only
public void btn_click(...){...}
我不确定是否使用普通的asp.net,但它在asp MVC中运行得很好

如果要使用cookies,请尝试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(...);
}
使用以下命令:

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();
    }
}

希望这不会用于生产代码?当然,这是为了学习。我应该在哪里重新分配HttpContext.Current.User?我试图在global.asax中使用Application_AuthenticateRequest事件来检查每个请求,但此事件中不存在会话。我在PostAuthenticateRequestglobal.asax分配。只需将HttpContext.Current.User=newwebuser。。。;不需要分配给会话