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"?

4

2 回答 2

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.

于 2012-06-04T15:25:41.207 回答
0

您是否尝试过使用 ProfileProvider?

您可以使用和自定义特殊属性,这由每个用户的会话管理。

获取值的示例:

HttpContext.Profile.GetPropertyValue["CustomProperty"]

在本视频中,您可以轻松实现、创建、配置和使用...

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

于 2012-06-04T15:11:04.747 回答