holding who's logged in.....

lidds

Junior Contributor
Joined
Nov 9, 2004
Messages
210
Could someone explain to me the best way of holding who is logged into your website. Have got a login page, but am unsure of how and the best way to hold user info between different pages???

I am new to asp, so be gentle and examples of code if possible would be great.

Cheers

Simon
 
There are several ways you can accomplish this.

One commonly used way is to use the Session object, which you might use (after a successful login) like:

[csharp]// where sUsername is a string holding the username
// where nUserId is an int holding the user's ID number

Session.Add("username", sUsername);
Session.Add("userid", nUserId);[/csharp]

It's up to you what you store off for user info. Session can hold objects too so if you have a user object you could store the entire user object off if you wanted to. You can get values out of session just as easily:

[csharp]string sUsername = Session["username"];
int nUserId = Session.Contents["userid"]; // variation[/csharp]

Sessions can expire so you'll usually want to check for nulls or wrap a try/catch around the code that grabs the values. In a robust app you might have the user re-login if their session expire.

Another similar way to track user info is with cookies. Cookies are a little more flexible. Cookies are always stored on the client machine (Sessions can be setup for different storage mechanics, but it's often server-side storage).

A simple cookie example:

[csharp]HttpCookie oCookie = new HttpCookie("logininfo");

oCookie["username"] = sUsername;
oCookie["userid"] = nUserId;
oCookie.Expires = DateTime.Now.AddHours(2);

Response.Cookies.Add(oCookie);[/csharp]

And to retreive values:

[csharp]HttpCookie oCookie = Request.Cookies["logininfo"];

string sUsername = oCookie["username"];
int nUserId = int.Parse(oCookie["userid"]);[/csharp]

And again - you usually want to check for null or use a try/catch because cookies can expire too.

The syntax would be similar if you're using VB.Net.

For more info on either, refer to MSDN, google, or search around here.

Paul
 
Back
Top