I\'m using FormsAuthentication and ASP.Net SqlMembership Provider. I would like to provide a functionality to redirect to LogIn page when the underlying Session is expired.<
Pawel's answer is partially correct, but you also need to set the Session lifetime to a value longer than the forms authentication cookie lifetime as well. The forms authentication timeout value only affects the lifetime of the authentication cookie. In the example he provided, the authentication cookie lifetime is 60 minutes but the default session lifetime is 20 minutes. If a user left their machine for more than 20 minutes their session data would be discarded, subsequent attempts to reference a value stored in session would result in an exception being thrown (for example System.NullReferenceException if attempting to .ToString() or a cast).
You can set this globally in your application by configuring the sessionState settings in your web.config file:
<sessionState
mode="InProc"
cookieless="false"
timeout="70"/>
Adding five or ten minutes to the session timeout provides a good buffer.
You don't need any custom code for this functionality, it's supported by the Framework. Just configure it in the web.config:
<authentication mode="Forms">
<forms defaultUrl="~/Default.aspx"
loginUrl="~/Login.aspx"
slidingExpiration="true"
timeout="60" />
</authentication>
With the configuration above, the user will be always redirected to the Login.aspx page when their session expires. There is a timeout of 60 minutes, and sliding expiration means that the timeout is extended each time the user makes a request to the web application, so if he stays active the session will not expire. A configuration like this gives you another advantage over what you tried to do - once the user logs in he will be automatically redirected back to the resource he originally requested. And you can always override and customize this behavior.