Storing and accessing a legacy UserID in asp.net membership

吃可爱长大的小学妹 提交于 2019-12-11 06:42:15

问题


I have a legacy UserID (int32) which I wish to link to asp.net membership. I have set up link tables on the database and I'm happy with that part. The question is where to store the UserID in the web application so that it is easily accessible when required.

I decided that the best place to store it is in the UserData part of the FormsAuthenticationTicket in the LoggedIn event of the Login Control. My first attempt to make this accessible was to extract it in the PreInit of my BasePage class. The trouble with this is that it gets messy when the UserID is required by UserControls.

Is it acceptable to just wrap it in a static method or property in a Utilities class, something like this:

    public static int UserID
    {
        get
        {
            int userID = 0;
            if (HttpContext.Current.User.Identity is FormsIdentity)
            {
                FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                FormsAuthenticationTicket ticket = id.Ticket;
                userID = Int32.Parse(ticket.UserData);
            }
            return userID;
        }
    }

This seems to work but I don't know if I'm breaking some unwritten rule here. I presume all this stuff is in memory so there's no great overhead in this access.


回答1:


Your code looks fine from a functional perspective (though I would clean it up a bit, but that's more a style thing).

You might consider making it an extension method, though, rather than just sticking it in a random utility class. Maybe an extension for the IIdentity class?

int myUserId = HttpContext.Current.User.Identity.MyUserId();

Using the UserData field is fine, I guess. Another option is to create your own IIdentity object with a custom Ticket and wrap them in a GenericPrincipal -- might be too much work for what you're after, though.



来源:https://stackoverflow.com/questions/9284277/storing-and-accessing-a-legacy-userid-in-asp-net-membership

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!