Search code examples
asp.netvb.netsessionsession-state

Starting an ending a user session


I am confused about user session management, I am using 2010 express and VB.

I have a function that sends the username and password to my database and a stored procedure and returns Boolean if user is valid or not.

My question if the user is valid how do you start a session. I set cookies to auto and session inproc as per msdn docs.

So though if my function returns true how do I commence a session?

So what is the .net class and method I call to do this. I assume most are using the prebuilt MS login solution and that's why I am struggling to get an answer.


Solution

  • Sessions are automatically started in ASP.NET once you configured them in the web.config file (I assume you've done this). Go to the Global.asax file in your project (or add one) to run extra code after the session was created. (Note: this doesn't mean the there was a login. Sessions are created automatically.)

    On a very primitive basis you could store the login information in the Session object:

    ' check login credentials
    Public Sub Login(user As String, pwd As String)
        Dim authenticated As Boolean = False
        ' db authentication check here
        If authenticated Then
            HttpContext.Current.Session("authenticated") = True
        Else
            Throw New Exception("not authenticated!")
        End If
    End Sub
    
    ' logout user
    Public Sub Logout()
        HttpContext.Current.Session("authenticated") = False
    End Sub
    
    ' check if user is logged in
    Public Function IsAuthenticated() As Boolean
        Return HttpContext.Current.Session("authenticated") = True
    End Function
    

    But as stated this is very simplistic. You're better off using some Session Management techniques such as those in this example.