ASP登录Web控件事件的行为不符合预期

时间:2010-10-30 03:13:56

标签: asp.net login controls session-variables

我有一个包含<asp:Login>网页控件的.aspx页面。

对于身份验证,我有另一个继承MyMembershipProvider类的类(System.Web.Security.MembershipProvider)。

登录过程运行正常 - 即MyMembershipProvider对象正确验证了用户名/密码。

我的问题是关于设置System.Web.SessionState.HttpSessionState.Session变量。

用户成功通过身份验证后(MyMembershipProvider类),我想为该用户创建自定义Session变量。

最初,我认为我可以在Session控件的<asp:Login>事件处理程序中设置LoggedIn变量 - 如下所示:

protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
    //Get the UserName of the authenticated user
    string userName = Thread.CurrentPrincipal.Identity.Name;

    //Call the business layer to get more info on the authenticated user
    Entities.User user = BizLayer.GetUser(userName);

    //Set session vars for the authenticated user
    Session["LastName"] = user.LastName;
    Session["FirstName"] = user.FirstName;
    Session["Email"] = user.Email;
}

我注意到的问题是,当LoggedIn事件被触发时,Thread.CurrentPrincipal.Identity.Name尚未设置为用户登录时使用的用户名。因此,调用BizLayer.GetUser()会返回一个空的User对象,当然会导致Session setter无用。

我的猜测是,由于我使用的是自定义MembershipProvider<asp:Login>事件处理程序(LoggedInAuthenticatedLoggingIn)无效因为我期待他们。

我应该使用另一个事件处理程序来设置Session个变量吗?或者,你能否指出我正确的方向,这将完成我所描述的同样的事情?

在听到更好的方法之前,我已实施以下内容:

我将DestinationPageUrl控件的<asp:Login>属性更改为指向将执行设置Session变量的页面。然后,在我设置Session vars之后,我致电Response.Redirect()以转到过去在DestinationPageUrl属性中设置的网页。

相关代码如下所示:

Login.aspx网页的登录控件类似于......

<asp:Login ID="LoginUser" runat="server" DestinationPageUrl="SetSessionVars.aspx">

SetSessionVars.aspx网页有一个设置会话变量并将用户重定向到某个页面的方法......

protected void Page_Load(object sender, EventArgs e)
{
    this.SetSessionVars();
    Response.Redirect("foo.aspx");
}

private void SetSessionVars()
{
    //Get the UserName of the authenticated user
    string userName = Thread.CurrentPrincipal.Identity.Name;

    //Call the business layer to get more info on the authenticated user
    Entities.User user = BizLayer.GetUser(userName);

    //Set session vars for the authenticated user
    Session["UserId"] = user.UserId;
    Session["LastName"] = user.LastName;
    Session["FirstName"] = user.FirstName;
    Session["Email"] = user.Email;
}

1 个答案:

答案 0 :(得分:1)

为什么不直接从登录表单中捕获用户名而不是从Thread.CurrentPrincipal.Identity.Name获取用户名?

ASP.NET中这些东西的顺序实际上并不直观,因为在Page_Load之前加载了标识,然后没有像你期望的那样在Logged_In事件中更新。

编辑:由于您不喜欢这样,在您的业务层中,您需要添加如下内容。

var genericIdentity = new System.Security.Principal.GenericIdentity(username);
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(genericIdentity, roles);
相关问题