我正在用WebForms中的VS2010开发一个C# web应用程序。我使用我的自定义登录方法对用户进行身份验证,我不想使用成员资格框架。在用户登录后,我想将用户数据存储为userId、用户名、姓氏、电子邮件等,这样我就可以在用户会话期间访问所有页面中的数据。
我怎么能这么做?我不想将用户数据存储在FormsAuthenticationTicket的FormsAuthenticationTicket属性中。
我找到了一种方法:是将用户数据存储在会话中还是使用自定义配置文件提供程序?,但我不知道如何实现它。
我有个问题:
1)在登录页面中,在检查db上的凭据后对用户进行身份验证: FormsAuthentication.SetAuthCookie(txtUserName.Value,true);现在,在我的默认页面中,我拥有:
FormsAuthenticationTicket票证= ((FormsIdentity)(User.Identity)).Ticket;我使用ticket.Name显示用户名。是对的吗?为什么要谈论使用Thread.CurrentPrincipal.Identity.Name的线程?
2)我在global.asax文件中有以下代码,用于读取用户角色并将其存储到HttpContext中:
void Application_AuthenticateRequest(对象发送方,EventArgs e) {
if (Request.IsAuthenticated) {
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnStr"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT Gruppi.Name FROM Ruoli INNER JOIN Gruppi ON Ruoli.GroupID = Gruppi.GroupID INNER JOIN Utenti ON Ruoli.UserID = Utenti.UserID AND Utenti.Username=@UserName", conn);
cmd.Parameters.AddWithValue("@UserName", User.Identity.Name);
SqlDataReader reader = cmd.ExecuteReader();
ArrayList rolelist = new ArrayList();
while (reader.Read()){
rolelist.Add(reader["Name"]);
}
// roleList.Add(reader("Name"))
string[] roleListArray = (string[])rolelist.ToArray(typeof(string));
HttpContext.Current.User = new GenericPrincipal(User.Identity, roleListArray);
reader.Close();
conn.Close();
}
}当您从我的global.asax文件而不是login.aspx页面中写入时,我可以将用户数据存储到会话中吗?
发布于 2013-08-06 17:03:41
为了便于调试,我建议使用会话外观设计模式在此描述,它将允许您以更有组织的方式使用HttpContext.Current.Session对象存储当前用户的数据。
例如,将有一个文件(例如,SessionFacade.cs)负责处理传递给或从Session传递的值;在您的示例中,它可能如下所示:
public static class SessionFacade
{
public static int UserId
{
get {
if (HttpContext.Current.Session["UserId"] == null)
HttpContext.Current.Session["UserId"] = 0;
return (int)HttpContext.Current.Session["UserId"];
}
set {
HttpContext.Current.Session["UserId"] = value;
}
}
// ... and so on for your other variables
}然后,在代码中的其他地方,一旦您检查凭据是否正常,您可以.
if (credentialsAreOk) {
SessionFacade.UserId = /* insert ID here */
// ...
}用于手动为会话对象分配值的...instead。这将确保Session中的变量具有正确的类型,并且在调试时更容易跟踪。然后,要从程序中的任何地方获取UserId,它就是SessionFacade.UserId。
(是的,片段来自于爱德华的回答;您仍然应该研究这个答案,因为它提供了关于WebForms工作方式的信息;请记住,在您的代码中手动调用Session对象可能会很麻烦,会话外观会使这个过程变得更干净)
发布于 2013-08-06 16:28:05
如果您所说的“VS2010 In C#的web应用程序”是指ASP.NET (MVC或ASP.NET),以及您指的是FormsAuthentication,那么您所需要做的就是在登录时将您以后需要的信息存储到会话对象上。
假设您使用的是ASP.NET经典,并且有一个登录页面

它有两个用户名和密码输入和一个名为“登录”的提交按钮。

在按钮的(服务器端) OnClick事件处理程序中,您应该执行如下操作:
public partial class Login : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}
private bool CheckUserPass(string username, string password) {
// access DB or some other form of storage service
return true;
}
protected void buttonLogin_Click(object sender, EventArgs e) {
bool credentialsAreOk = this.CheckUserPass(
this.textBoxUsername.Text,
this.textBoxPassword.Text
);
if (credentialsAreOk) {
this.Session["EMAIL_ADDRESS"] = "SomeEmail@SomeEmailProvider.com";
this.Session["OTHER_INFORMATION_KEY"] = "Some other stuff which you have access to during the login process";
this.Session["TIME_OF_LOGIN"] = DateTime.UtcNow;
FormsAuthentication.RedirectFromLoginPage(this.textBoxUsername.Text, createPersistentCookie: false);
}
}
} 因此,简而言之,如果您使用的是FormsAuthentication,那么用户名可以以您告诉FormsAuthentication系统当前会话应该从未经身份验证的转换为身份验证的方式存储到会话上:
FormsAuthentication.RedirectFromLoginPage(this.textBoxUsername.Text, createPersistentCookie: false);其他信息可以放在会话对象上(就像将键值对添加到字典中一样):
this.Session["TIME_OF_LOGIN"] = DateTime.UtcNow;虽然很明显,您以后如何访问相同的信息(针对相应的用户):
DateTime whenDidILogin = (DateTime) this.Session["TIME_OF_LOGIN"];
// this line of code can be used in any other page
// at any later time - it's like you have a global set of variables
// which exist for each and every distinct session you might have提到用户名(如果不像其他示例一样显式地放置在会话对象上)可能很重要,可以使用Thread.CurrentPrincipal静态属性访问,如下所示:
using System.Threading;
public void SomeWhereInYourApp() {
bool wasIAuthenticated = Thread.CurrentPrincipal.Identity.IsAuthenticated;
string whatIsMyUsername = Thread.CurrentPrincipal.Identity.Name;
// do something with that information
}发布于 2013-08-06 16:14:41
成员资格提供程序可以帮助您存储数据,也可以用于身份验证。就像这样:-
Session["UserName"] = Membership.GetUser().UserNamehttps://stackoverflow.com/questions/18085254
复制相似问题