views:

57

answers:

4

When a user log into my asp.net site I use the following code:

FormsAuthentication.RedirectFromLoginPage(userid, false);

As I often need to use the userid I can then later get the userid by:

string userid = System.Web.HttpContext.Current.User.Identity.Name;

Now I also want to show the logged in username on each page and my questions is therefore where do I place the username best if I need to use it on every page. User.Identity.Name is already taken by the userid so I can't use that one. Another solution would be to get the username from the database on each page, but that seems like a bad solution.

So: Is the best way to use Sessions to store the username?

+1  A: 

You can store just about anything in SessionState in asp.net. Just be careful and store the right things in the right places (you can also use ViewState to store variables.

Check this out for how to use SessionState to store and retrieve variables across postbacks.

Ryan Hayes
A: 

Using sessions isn't a bad idea but make sure to check for NULL when retrieving the values for when the sessions time out.

Or you could pass the variable through in the URL e.g

/Set
Response.Redirect("Webform2.aspx?Username=" + this.txtUsername.Text);

/Read
this.txtBox1.Text = Request.QueryString["Username"];
gazamatazzer
A: 
public string currentUser
{
    get { return Session["currentUser"] as string; }
    private set { Session["currentUser"] = value; }
}
Jeff Dege
+2  A: 

There are essentially 5 different ways to store information, each with it's own benefits and drawbacks.

  1. Class member variables. These are only good for the life of one page refresh.
  2. HttpContext variables. Like class member variables, only good for one page refresh.
  3. ViewState, these are passed from page to page to keep state, but increase the size of the downloaded data. Also, not good for sensitive information as it can be decoded.
  4. Cookies. Sent on each page request. Also not good for sensitive information, even encrypted.
  5. Session. Not passed to the end user, so good for sensitive information, but it increases the resource usage of the page, so minimizing usage for busy sites is important.
Mystere Man