Asp.net, where to store the username of the logged in user?

When a user logs in to my asp.net site, I use the following code:

FormsAuthentication.RedirectFromLoginPage(userid, false);

As I often need to use userid, I can then get the user ID:

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

Now I also want to show the registered username on each page, and so I ask the question where is the best place to put the username if I need to use it on every page. User.Identity.Name is already being used by the user id, so I cannot use it. Another solution would be to get the username from the database on each page, but this seems like a bad solution.

So: the best way to use sessions to store a username?

+3
source share
4 answers

You can store almost all SessionState in asp.net . Just be careful and keep the right things in the right places (you can also use ViewState to store variables.

Check this to use SessionState to store and retrieve variables via postback.

+1
source

There are essentially 6 different ways of storing information, each of which has its own advantages and disadvantages.

  • Class variables. This is only useful for updating a single page.
  • HttpContext. - , .
  • ViewState, , , . , , .
  • Cookies. . , .
  • Session. , , , .
  • cookie - cookie, IIdentity, , ​​ . .
+4
public string currentUser
{
    get { return Session["currentUser"] as string; }
    private set { Session["currentUser"] = value; }
}
+1
source

Using sessions is a good idea, but be sure to check for NULL when receiving values ​​when the session timeout.

Or you can pass the variable through a URL, for example.

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

/Read
this.txtBox1.Text = Request.QueryString["Username"];
0
source

Source: https://habr.com/ru/post/1767180/


All Articles