0

我一直在研究一个 ASP.NET 应用程序,并且我已经成功地创建了一个登录并注册了一个使用 C# 作为服务器端代码链接到 SQL 数据库的网页。

问题:
我找不到在打开不同页面时让用户保持登录状态的好方法,最好的方法是什么,但可以 100% 自定义,最好使用“登录控件”。

谢谢你的时间!

4

2 回答 2

0

我使用了 HttpSession,存储了登录用户的电子邮件。之后,在每个页面中,您必须检查它是否不为空。我发布一个例子

public class SessionProvider
{

    public static void Put(string key, string value)
    {
        HttpContext.Current.Session[key] = value;
    }
    public static void PutObject(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }

    public static void Delete(string key)
    {
        HttpContext.Current.Session.Remove(key);
    }

    public static string Get(string key)
    {
        if (HttpContext.Current.Session[key] == null)
            return null;
        else
            return HttpContext.Current.Session[key].ToString();
    }

    public static object GetObject(string key)
    {
        return HttpContext.Current.Session[key];
    }

    public static void Abandon()
    {
        HttpContext.Current.Session.Abandon();
    }

}
于 2013-08-26T12:42:42.917 回答
0

用户被绑定到一个Session. 所有页面都有该属性可用。它是一个HttpSessionState对象,您可以在其中存放登录的用户信息。现在,您可以通过构建一个具有实际将数据拉出会话的访问器的User类来封装大量工作。static例如:

public static class User
{
    public static bool IsAuthenticated
    {
        get
        {
            var session = HttpContext.Current.Session;
            return !string.IsNullOrEmpty(session["LoggedInUser"]);
        }
    }

    public static string UserName
    {
        get
        {
            return session["LoggedInUser"];
        }
    }

    public static bool Login(string userName, string password)
    {
        // login (i.e. verify the user name and password

        // build some kind of session indicator
        HttpContext.Current.Session["LoggedInUser"] = userName;

        return true;
    }

    public static void Logout()
    {
        if (!IsAuthenticated) { return; }
        HttpContext.Current.Session.Abandon();
    }
}

所以现在从页面中你可以做这样的事情:

User.Login(txtUserName.Text, txtPassword.Text);
于 2013-08-26T12:41:49.897 回答