ASP.NET Tip: Using the LoginName and LoginStatus Controls

Besides the new LoginView control that Microsoft added to ASP.NET 2.0, you could use a couple of handy controls in conjunction with your web site security: LoginName and LoginStatus.

The LoginName control simply displays the user name if the user is logged in. If the user isn’t logged in, nothing is rendered to the page. You can combine this with the LoginView control as follows:

<asp:LoginView ID="ctlRightNavbar" runat="server">
   <AnonymousTemplate><a href="/login.aspx" class="navbar">
      User Login</a></AnonymousTemplate>
   <LoggedInTemplate>
      <a href="/logout.aspx" class="navbar">
         Logout <asp:LoginName ID="ctlUserName" Runat="server" /></a>
   </LoggedInTemplate>
</asp:LoginView>

If the user is logged in as Eric, the text Logout Eric will be displayed. The only downside to this control is that if you are not storing the actual user name in User.Identity.Name, the control won’t get you anything. In some of my applications, I store the user’s ID number in User.Identity.Name, so the result for my application is Logout 123, for instance.

The LoginStatus control is designed to do the same thing as the LoginView control. Its default behavior is to show a link to a login page or logout page, depending on the user’s authentication status. It has properties for images and text to be shown in each state, as well as events to which you can add code. Here’s LoginStatus code that does the same thing as the previous LoginView example:

<asp:LoginStatus ID="ctlLogin"
                 runat="server"
                 LoginText="User Login"
                 LogoutText="User Logout"
                 LogoutPageUrl="/logout.aspx"
                 LogoutAction="Redirect" />

Each of the control’s properties lets you control each behavior. The property that is “missing” is the LoginPageUrl, but that property is automatically pulled from your Web.config file to determine the login page.

The LogoutAction property is interesting in that you can choose to simply refresh the existing page after logout (use a value of Refresh or leave it empty), go to the logout page (use the value of Redirect), or bounce back to the login page (use a value of RedirectToLoginPage).

The other interesting thing is that this control resolves the issue of being able to see unauthenticated content after logout; the LoginView control didn’t do that.

About the Author

Eric Smith is the owner of Northstar Computer Systems, a web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic. Send him your questions and feedback via e-mail at questions@techniquescentral.com.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read