0

i am new to asp.net. my question is that how one can save login userid in asp.net webform? code i am writing in asp.net webform is:

 foreach (var s in db.Users)
        {
            if (tbUserName.Text==s.user_name && tbPassword.Text == s.user_password)
            {
                if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
                {
                    FormsAuthentication.SetAuthCookie(tbUserName.Text, false);
                    Response.Redirect("~/");
                }
                else
                {
                    FormsAuthentication.RedirectFromLoginPage(tbUserName.Text, false);
                }
                flag = 1;
                break;
            }
            else
                flag=0;
        }
          if(flag==0)
           {
                tbUserName.ErrorText = "Invalid user";
                tbUserName.IsValid = false;
            }

    }
user2835256
  • 407
  • 2
  • 13
  • 27

2 Answers2

5

As Tim said, you can get the authenticated user with

User.Identity.Name

You can also get the AuthenticationType and IsAuthenticated properties from the same object.

A suggestion would be to NOT query your DB for all of the users and then loop through them for the correct one. Based off of the user input, you should query the db for the one and only user which matches the form post.

Based off of what you wrote, it looks like the passwords are in clear text and not encrypted, which is a huge security issue. Being new to .Net, take a look at the .Net Membership Providers or SimpleMembership or a comparable pattern.

Good luck!

ohiodoug
  • 1,493
  • 1
  • 9
  • 12
  • can you please explain me `A suggestion would be to NOT query your DB for all of the users and then loop through them for the correct one. Based off of the user input, you should query the db for the one and only user which matches the form post.` :) – user2835256 Nov 28 '13 at 06:35
2

I would suggest you look at using the Session object to store the user ID. A Session will be available throughout that user's session on the site. Thus, you can call Session anywhere in your site's code to reference that user ID.

For example, to store the id, simply do this, pretend we're in Page_Load()

Session["UserId"] = userID // Or wherever you get the ID from.

then in your code behind, you can do this:

string userId = Session["UserId"]

If the user ID is a number, say an int, then you will need to cast the userID:

int userId = 0;

int.TryParse(Session["UserID"], out userID)

Quick dirty link to a Session example :

http://asp.net-tutorials.com/state/sessions/

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
  • where to write `Session["UserId"] = userID`? – user2835256 Nov 26 '13 at 20:59
  • Hmmm, I've made the assumption that UserID is a number. However, as pointed out by others, if the UserID is that user's name, then you can use `User.Identity.Name` rather than using `Session`. – Jason Evans Nov 26 '13 at 21:01
  • 1
    Ahhh, OK cool. So using `Session` is still a valid idea for you. – Jason Evans Nov 26 '13 at 21:02
  • it says: Error 22 The name 'userID' does not exist in the current context – user2835256 Nov 26 '13 at 21:06
  • You have to first create an entry for `UserID` in `Session` by calling `Session["UserID"] = userID`. I think you may have just tried `int userId = Session["UserID"]` where "UserID" does not exist yet in the session. – Jason Evans Nov 26 '13 at 21:08
  • Will your solution ever need to be load-balanced across multiple web heads? If so, the session may not be your best choice. – ohiodoug Nov 26 '13 at 21:14
  • True, there are caveats to using `Session` regards load balancing, which is a big topic in itself. Other then Session though, how else could userID be stored? I'd like to help the question author will all options. – Jason Evans Nov 26 '13 at 21:16
  • 3
    On an incoming request you can check your user and if storing the id is important, add it to the HttpContext.Items dictionary. This option won't break down across load-balancing. Plus it doesn't require any special session clearing logic if the user logs out, the items collection is disposed when the request goes out of scope. – ohiodoug Nov 26 '13 at 21:20
  • 1
    Ahh HttpContext.Items, forgot about that. – Jason Evans Nov 26 '13 at 22:12
  • Jason and Doug - see `The redirect generates a new HttpContext which is why the items in it are lost - the redirect effectively tells the browser the next URL to request, and when it does it loses the context of the previous request that triggered the redirect.The session persists across requests (typically using a sessionID cookie to tie the user to values on the server), and is thus still available.` http://stackoverflow.com/questions/16697601/response-redirect-does-not-preserve-httpcontext-current-items - So i should go for sessionor httpcontext.items to store userid? – user2835256 Nov 28 '13 at 06:52