I have a web site that uses Membership and form authentication:
ASP.NET Page:
<asp:LoginView
ID="HeadLoginView" ...
<AnonymousTemplate>
<asp:Login ID="LoginUser" OnLoggedIn="LoginUser_LoggedIn" ... >
<LayoutTemplate>
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label>
<asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox>
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
<asp:TextBox ID="Password" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
<asp:CheckBox ID="RememberMe" runat="server"/>
<asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Remember me.</asp:Label>
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Login" style="width:100%; height:35px"/>
</LayoutTemplate>
</asp:Login>
</AnonymousTemplate>
...
</asp:LoginView>
Code behind:
protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
MembershipUser user = Membership.GetUser();
if (Roles.IsUserInRole(user.UserName, "User"))
{
// Do something and redirect to user page...
}
if (Roles.IsUserInRole(user.UserName, "Admin"))
{
// Do something and redirect to admin page...
}
}
The problem is that Membership.GetUser() always returns null. I tried to get username with Page.User.Identity.Name but it is always empty string. Is there a way to find username of currently logged in user or even better: define after-login behavior of <asp:LoginView> or <asp:Login>?
Edit:
MSDN: Login.LoggedIn Event Occurs when the user logs in to the Web site and has been authenticated. (link) So the problem is that why after authenticating user Membership.GetUser() returns null?
One of my colleagues said that instead of using Membership.GetUser() use Membership.GetUser(UserNameTextBox.Text) and it is okay because user is authenticated with this username BUT the problem is that I can not find a way to get Username.Text. I used findControl() and got error.
Any Idea?
Finally I found the solution based on the Idea of @LolCoder: