1

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.

Fruitbat
  • 764
  • 2
  • 5
  • 19

1 Answers1

3

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.

RickNZ
  • 18,448
  • 3
  • 51
  • 66
  • Extension methods are fairly new to me, so I had to do a bit of reading - http://msdn.microsoft.com/en-us/library/bb383977.aspx for future reference. That does look nice. A pity they don't have Extension Properties (yet). BTW, aside from adding error handling, what sort of "clean it up a bit" did you have in mind. I didn't think it looked that bad. – Fruitbat Feb 15 '12 at 10:25
  • 1
    For cleanup, I would use "as" instead of "is", avoid referencing HttpContext.Current.User twice, and use TryParse instead of Parse. – RickNZ Feb 15 '12 at 17:38