7

I'm new to asp.net and C# and I want to ask how to implement a session login using asp.net and C#.

Please advise.

Thanks.

4 Answers 4

12

In C# you can define a session variable like this:

Session["userame"]= txtusername.Text;

where txtusername is a text box. In another page you can call it as:

string usrname = Session["username"].ToString();

To check whether a user is logged in or not, in a particular page; you'll have to check if this session is empty or not. If the session is null then redirect the user to login page else he/she can view the page. Same logic applies to all the pages where you want to implement the session validation. Sample (on Page_Load event):

if (Session["username"] == null)
   Response.Redirect ("Login.aspx");

Hope it helps... :)

Sign up to request clarification or add additional context in comments.

7 Comments

Is there a better way than checking "Username"? I feel like if there was some other bug (Such as allowing null usernames) then its not reliable... Some kind of flag? Either here, on in the cookie itself?
@Worthy7 you can use asp.net's internal profile feature. Follow this link: msdn.microsoft.com/en-us/library/2y3fs9xs.aspx
In the end I entirely ditched sessions and moved to encrypted tokens.
@Worthy7 Well... You did ask for session implementation in the question and hence the answer...
asked 8 years ago, not by me
|
6

The question is broad answer, in Simply you can follow like this

  • Create database, user table in sql server or any database of your choice
  • Create the login form with userid and password
  • Check them with database for user availability
  • If User exist and password matches create a session, like Session.Add ("Userid", txtUserid.Text);
  • In other pages (restricted pages where only registered users allowed) write this code in every page load event

    if (Session["Userid"] == null) Response.Redirect ("Login.aspx");

Comments

3
Session["login_user"] = "[username]";
string username = Session["login_user"].ToString().Trim();

Comments

-1

Easiest way to implement session is as following:

Session["SessionName"] = Value;

For retrieving value

String variable = Session["SessionName"].ToString();

Note: Session variable can be of any type.

Generally session is used for checking whether the user is logged in or not.

1 Comment

This questions is over 9 years old and your answer adds nothing new to it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.