totoz
totoz

Reputation: 31

ASP.NET problem with session / redirect to page

Hi I have problem with store user name in Session. On log on page I store user name to session. User input credentials on logon page and then is redirect on default page. I need in class Default access to variable store in session.

Logon.aspx

<script runat="server">
    void Login_Click(object sender, EventArgs e)
    {
                 Session["user"]  = tbUserName.Text;

                //You can redirect now.
                Response.Redirect(FormsAuthentication.GetRedirectUrl(tbUserName.Text, 
false));
}
</script>

secod main page is here:

Default.aspx-Default.aspx.cs

public partial class Default : Page, 
    IHttpHandler, System.Web.SessionState.IRequiresSessionState 
{
      string userName = (string) (Session["user"]);
}

but result is that userName is empty.

Web config is here:

<sessionState cookieless="true" regenerateExpiredSessionId="true" />

Thank you for advice.

Upvotes: 2

Views: 1613

Answers (3)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

Why not get it directly from HttpContext HttpContext.Current.User.Identity.Name

Edit: I guess you are trying to get it at page level instead of in page_load or another place. That's why you are not getting a session value.

I hope below will work for you

 protected void Page_Load(object sender, EventArgs e)
 {
     string userName = (string) (Session["user"]);
 }

Upvotes: 1

Samu Lang
Samu Lang

Reputation: 2271

Update: This is incorrect.

You're losing the (cookieless) session when you redirect. Cookieless sessions are maintained in the URL, and are lost when you explicitly redirect, so there is nothing in the session on your second page.

Upvotes: 0

Eben Roux
Eben Roux

Reputation: 13256

If the snippet is on the module level (as alluded to by Bala R in the comments) the session state has probably not been set yet. Try getting it in a method that is part of the page life cycle (like page_load, etc.).

Upvotes: 1

Related Questions