ASP.NET 2.0 has added a number of controls to simplify developers' lives when it comes to routine, repeated tasks that are common to web applications. This tip discusses the LoginView control, which works hand in hand with the other security features of ASP.NET.
Most web applications that have any sort of user authentication need to show different content based on whether or not the user is logged into the application. The simplest example is showing a Log In link to unauthenticated users and a Log Out link to users who have logged in. In previous versions of ASP.NET, you could implement this with a panel control or other control that would show or hide based on whether there was a value in User.Identity.Name. Although the old method will still work, the LoginView control does this work for you. Here's a code sample that shows how this control works:
<asp:LoginView ID="ctlRightNavbar" runat="server"> <AnonymousTemplate><a href="/login.aspx" class="navbar"> User Login</a></AnonymousTemplate> <LoggedInTemplate><a href="/logout.aspx" class="navbar"> User Logout</a></LoggedInTemplate> </asp:LoginView>
This control requires no back-end code to function properly, other than having the user logged in or not. If ASP.NET determines that a user is logged in, the LoggedInTemplate contents will display. If not, the AnonymousTemplate will show. Any controls or HTML markup can be put in the templates, just like any other templated control.
The only minor issue I've had with this control is that if you log the user out on the logout.aspx page, the LoggedInTemplate will show up on the logout page. This is because the LoginView control is rendered before the code in the page is executed. In my testing, it doesn't matter what you use—even if you put the code in the OnPreInit event, which in theory should run first. However, this is a minor issue because most people don't log out of sites, and ASP.NET security will catch the user if he or she tries to perform an authenticated function after the user has logged out. The user will be redirected back to the login page automatically.
This handy control can get rid of some of the tedious code you've probably got in at least one of your ASP.NET applications. Microsoft listened to developers and added controls that we wanted. This is a nice addition to the toolbox.
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 email@example.com.