2

Should I be using Shared, or just a Public function and initiate a class when needed? I have read a number of articles, but still cant get my head around the best option here.

Here is the code I want to get. The userid in question is a string that's set when the user logs in. As I may need the userid in a number of pages, I want to add it in a class.

Public Shared ReadOnly Property userid As String
    Get
        Dim ck As HttpCookie = HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName)
        Dim tkt As FormsAuthenticationTicket = FormsAuthentication.Decrypt(ck.Value)
        Return tkt.Name
    End Get
End Property
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
user984314
  • 155
  • 1
  • 3
  • 14
  • The key to this is the context the call operates in. In this case the property reads from a session value so it would work fine. That's not always the case. Take a look at this question I asked a few years ago: http://stackoverflow.com/questions/4026785/how-do-static-properties-work-in-an-asp-net-enviroment – asawyer Apr 09 '13 at 20:19

2 Answers2

1

I would almost never say that you should leverage a Shared member when dealing with authentication - but since you're using Cookies I can't see any reason this code wouldn't work as is and make it easier to access.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
1

It is perfectly fine and acceptable. You can see accessing HttpContext.Current inside static method in a lot of open source projects.

FYI: HttpContext.Current must be on current calling thread, so make sure to check HttpContext.Current is not null.

Win
  • 61,100
  • 13
  • 102
  • 181