Redirect to login page when session expires – Asp.net Web forms

In this article, I will explain you how to redirect to login page when session expires and navigate to last visited page after login in.

In asp.net, we have the feature to get the rawUrl from the application, by using the functionality; we are going to perform the task.

string OriginalUrl = HttpContext.Current.Request.RawUrl;
string LoginPageUrl = "/Login.aspx";
HttpContext.Current.Response.Redirect(String.Format("{0}?ReturnUrl={1}", LoginPageUrl, OriginalUrl));

In the above code, originalUrl will contain the current page name, while redirecting to login page, we append the returnUrl to the page.

After login, capture the return url parameter and redirect to the last visited page, Refer the below code,

if (Request.QueryString["ReturnUrl"] != null)
{
     Response.Redirect(Request.QueryString["ReturnUrl"]);
}