Storage and access to obsolete UserID in asp.net membership

I have an obsolete UserID (int32) that I want to associate with asp.net membership. I have created link tables in the database and I am happy with this part. The question is where to store the user ID 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 form in the LoggedIn event to log in. My first attempt to make this available is to retrieve it in the PreInit of my BasePage class. The problem is that it becomes messy when UserID is required by UserControls.

Is it possible to simply wrap it in a static method or property in a Utility 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; } } 

It seems to work, but I don't know if I can break some unwritten rule here. I assume that all this happens in memory, so there is no big expense in this access.

+1
source share
1 answer

Your code looks great from a functional point of view (although I would have cleaned it up a bit, but it is rather a style).

However, you might consider making it an extension method, rather than just sticking to it in an arbitrary utility class. Perhaps an extension for the IIdentity class?

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

Using the UserData field is fine, I think. Another option is to create your own IIdentity object with a custom Ticket and wrap them in a GenericPrincipal - maybe there is too much work for what you are after.

+3
source

Source: https://habr.com/ru/post/1396657/


All Articles