Application Cache in .asmx page gets cleared on each function call

31 Views Asked by At

I'm encountering an issue with the application cache in my .asmx page, and I'm seeking help to understand and resolve the problem. I have two functions within the same .asmx file, one for retrieving an access token (GetAccessToken) and another for saving a web order (SaveWebOrderTest). My goal is to store the access token in the application cache so that it persists across different function calls.

Here's a simplified version of my .asmx file:

Function GetAccessToken(username As String, password As String) As String
 
 Try
     If Not IsTokenValid() Then
         ' Si le token a expiré ou n'est pas encore récupéré, en obtenir un nouveau
         Dim newToken As String = RetrieveNewAccessToken(username, password)
         LogFile.writeInfo("NEW TOKEN " & newToken)

         If newToken IsNot Nothing Then
           
             ' Stocker le token dans le cache d'application
             HttpContext.Current.Application("AccessToken") = newToken
             HttpContext.Current.Application("AccessTokenExpiration") = DateTime.Now.AddDays(14)

       
             ' Parcourir les clés du cache
             For Each key As String In HttpContext.Current.Application.AllKeys
                 ' Récupérer la valeur associée à chaque clé
                 Dim value As Object = HttpContext.Current.Application(key)

                 ' Enregistrer la clé et la valeur dans le fichier de journal
                 LogFile.writeInfo($"Application Cache Key: {key}, Value: {value?.ToString()}")
             Next
         Else
             ' Gére le cas où la récupération du token échoue
             Return Nothing
         End If
     Else
         LogFile.writeInfo("token existant " & DirectCast(HttpContext.Current.Session("AccessToken"), String))
     End If
     ' Renvoie le token actuel
     Return DirectCast(HttpContext.Current.Session("AccessToken"), String)
 Catch ex As Exception
     Return ""
 End Try
 End Function
 
 Function IsTokenValid() As Boolean
    Try      
        If HttpContext.Current.Application IsNot Nothing Then
            LogFile.writeInfo("Application Cache existant ")
            ' Parcourir les clés du cache
            For Each key As String In HttpContext.Current.Application.AllKeys
                ' Récupérer la valeur associée à chaque clé
                Dim value As Object = HttpContext.Current.Application(key)
            Next

            ' Récupérer le token depuis le cache d'application
            Dim storedToken As String = DirectCast(HttpContext.Current.Application("AccessToken"), String)
            Dim storedExpiration As DateTime = DirectCast(HttpContext.Current.Application("AccessTokenExpiration"), DateTime)

            If Not String.IsNullOrEmpty(storedToken) AndAlso storedExpiration > DateTime.Now Then
                ' Le token est valide
                Return True
            Else      
                Return False
            End If          
        Else
            ' Le cache d'application n'existe pas
            LogFile.writeInfo("Application Cache is not available.")
            Return False
        End If
        'End If
    Catch ex As Exception
        LogFile.writeInfo("error IsTokenValid " & ex.Message)
        Return False
    End Try
End Function

  <WebMethod(EnableSession:=True)>
Function SaveWebOrderTest()
        Dim apiUrl As String = ConfigurationSettings.AppSettings("webapicaisse") & "/salesorders/ticketmobile"

        LogFile.writeInfo("Application Cache at Start:")
        CheckSession()
        Dim token As String = GetAccessToken("******", "****")
        LogFile.writeInfo("Application Cache at END :")
        CheckSession()
End Function

<WebMethod(EnableSession:=True)>
Public Function CheckSession() As String
Try
    ' Vérifier HttpContext.Current
    If HttpContext.Current IsNot Nothing Then     

        ' Vérifier les données du cache de l'application
        If HttpContext.Current.Application IsNot Nothing Then
            LogFile.writeInfo("Application Cache Data:")
            LogFile.writeInfo($"AccessToken: {If(HttpContext.Current.Application("AccessToken") IsNot Nothing, DirectCast(HttpContext.Current.Application("AccessToken"), String), "Empty or Nothing")}")
            LogFile.writeInfo($"AccessTokenExpiration: {If(HttpContext.Current.Application("AccessTokenExpiration") IsNot Nothing, DirectCast(HttpContext.Current.Application("AccessTokenExpiration"), DateTime).ToString(), "Empty or Nothing")}")
        Else
            LogFile.writeInfo("Application is null.")
        End If
    Else
        LogFile.writeInfo("HttpContext.Current is null.")
    End If

    ' Vérifier les données du cache d'application
    LogFile.writeInfo("Cache Data:")
    LogFile.writeInfo($"AccessToken: {If(HttpContext.Current.Cache("AccessToken") IsNot Nothing, DirectCast(HttpContext.Current.Cache("AccessToken"), String), "Empty or Nothing")}")
    LogFile.writeInfo($"AccessTokenExpiration: {If(HttpContext.Current.Cache("AccessTokenExpiration") IsNot Nothing, DirectCast(HttpContext.Current.Cache("AccessTokenExpiration"), DateTime).ToString(), "Empty or Nothing")}")


Catch ex As Exception
    LogFile.writeInfo($"Error in CheckSession: {ex.Message}")
End Try

Return "CheckSession completed"
End Function

The issue I'm facing is that after calling SaveWebOrderTest, the data stored in the application cache, specifically the access token, seems to be cleared or inaccessible when I subsequently call CheckSession. I've verified that the access token is correctly stored in the application cache during the execution of SaveWebOrderTest.

I want to emphasize that my GetAccessToken function successfully returns a token. I've also experimented by placing the functions (non-web method) in a shared class, but this didn't resolve the issue either.

I've checked my web.config settings, and everything seems to be in order. Is there a reason why the application cache is behaving unexpectedly, and is there a way to ensure data persistence across function calls?

Any guidance or insights into this issue would be greatly appreciated.

Thank you!

0

There are 0 best solutions below