1

I was thinking yesterday how to solve this issue, because everything what i give or check about user is depended of his ProviderUserKey (ID).

So i made one static function like

public static Guid GetUserID()
{
    string UserID = string.Empty;

    if(HttpContext.Current.Session["UserID"] != null)
    {
        UserID = HttpContext.Current.Session["UserID"].ToString();
    }


    if(!string.IsNullOrEmpty(UserID))
    {
        return new Guid(UserID);
    }

    UserID = Membership.GetUser().ProviderUserKey.ToString();
    HttpContext.Current.Session["UserID"] = UserID;
    return new Guid(UserID);
}

Main point of this class is to reduce database connections to check/get user ID.

My problem with this function is not that this is not working, my problem is what if logged user log out and log with another account?

Or Is it better to add session value on log in and clear session value on log out?

Where you can see any other problem with this kind of "Get User ID"?

Novkovski Stevo Bato
  • 1,013
  • 1
  • 23
  • 56
  • Not really a solution to your problem, but there's no reason to store the UserID as a string and convert back and forth. Just store it as a Guid and cast it as a Guid when you return it. – Erik Funkenbusch Jun 04 '12 at 15:29

2 Answers2

0

have you tried using the ProfileProvider?

you can use and customize with special properties and that's is managed by session each user.

example to get values:

HttpContext.Profile.GetPropertyValue["CustomProperty"]

In this video you can lean to implement it, create, configure and use...

http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-a-custom-profile-provider

Zach dev
  • 1,610
  • 8
  • 15
  • I don`t use .net profile, i use custom profile with custom database table. – Novkovski Stevo Bato Jun 04 '12 at 15:27
  • you can use the source of anything to the profile provider, it's simple just create your own profile provider inherits from System.Web.Profile.ProfileProvider and overrides the functions that you need like GetPropertyValues from you custom database who could be anything (MySql, SqlServer, WebServices, files, etc). – Zach dev Jun 04 '12 at 15:57
0

If you log the user out then you should also be killing the session. When you login as another user you would also have the session reinitialized.

Note you'll want to keep the session and forms auth timeouts (assuming you are using forms auth) in sync with each other:

How can I handle forms authentication timeout exceptions in ASP.NET?

This should help keep the session in line with the forms auth token. You'll in turn need to kill the session on logout and intialize it upon login.

Another alternative is to implememt your own membership provider that caches this key to prevent constant db hits.

Community
  • 1
  • 1
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71