SHEKHAR SHETE
SHEKHAR SHETE

Reputation: 6056

How to Redirect or Close Browser after Session TimeOut in ASP.NET?

I have a Catcha value( Security Code ) that is store in Session on PageLoad and that is going to be used when user clicks the search button. If the User is IDLE for more than 20 Min the value of Session is get expired. And when user clicks on Search Button. It Throws error " Object Reference Not Set To an Instance of an Object".

On PageLoad:

 if (!IsPostBack)
        {
            Session["CaptchaImageText"] = new RandomGen().GenerateRandomCode();

        }

On SearchButtonClick event:

if (SecurityCodeTextBox.Text.Trim() == Session["Captcha"].ToString())
        {
            return true;
        }
        else
        {
            return false;
        }

Here i get error "Object Reference Not Set To an Instance of an Object". i have also checked wheather the Session["Captcha"]!= null. But still it shows the same error.

How to Redirect or show a message that "Session Timeout !Visit again" and close the Browser.

Thanks in Advance!

Upvotes: 0

Views: 2870

Answers (2)

Jaime Torres
Jaime Torres

Reputation: 10515

Your code looks like you're inconsistent with your Session variable naming (I'm a strong proponent of constants for these).

That being said, the easiest way to handle your situation is

private void Page_Load(object sender, System.EventArgs e)
{     
    Response.AddHeader("Refresh",Convert.ToString((Session.Timeout * 60) + 5)); 
    if( string.IsNullOrEmpty(Session["Captcha"] as string) ) 
    {
         Server.Transfer("RedirectPage.aspx");
    }
}

That will cause a page redirect on session expiration.

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38608

TO close the browser, you need a client-side script... there is no way to do it by server-side, so, you can generate some javascript calling window.close();. For th message error, check if the Session[] is not null, if you call some method of this and it's null, you will get this kind of exception. Try something like this:

if (Session["Captcha"] == null)
{
   Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Session Timeout! Visit again.'); window.close();", true);
   return false;
}

return (SecurityCodeTextBox.Text.Trim() == Session["Captcha"].ToString());

Upvotes: 0

Related Questions