2016-09-22 38 views
0

我想在Web服務的所有Web方法中添加緩存。但我不知道正確的做法...Web服務方法(vb)上的緩存返回值

任何想法我能爲此做什麼?謝謝 !

這裏是我的代碼..

Dim _cache As Cache = New Cache() 
<WebMethod> 
Public Function GetAllSpeakers(SubSite As String, MyUsername As String, MyPassword As String) As String 
    If ValidateUser(MyUsername, MyPassword) Then 

     Dim cachedSpeakers As String 
     cachedSpeakers = CStr(_cache("CacheSpeakers")) 

     If (cachedSpeakers Is Nothing) Then 
     Try 
      Dim passWordEnc As SecureString = New SecureString() 
      For Each c As Char In Password.ToCharArray() 
       passWordEnc.AppendChar(c) 
      Next 

      Dim subContext As ClientContext = New ClientContext("url") 
      subContext.Credentials = New SharePointOnlineCredentials(Username, passWordEnc) 

      Dim json As String = JsonConvert.SerializeObject(LibraryMethods.Methods.GetSpeakers(subContext)) 

      _cache.Insert("CacheSpeakers", json, 
      Nothing, System.Web.Caching.Cache.NoAbsoluteExpiration, 
      New TimeSpan(0, 30, 0)) 

      Return json 

     Catch ex As Exception 
      Return "ERROR: " & ex.InnerException.ToString 
     End Try 
    Else 
     Return _cache("CacheSpeakers").ToString() 
     End If 
    Else 
     Return "AUTHENTICATION FAILED" 
    End If 
End Function 

回答

0

我做出一些改變我的奧姆方法和現在緩存的工作! 我使用HttpRuntime.Cache。

<WebMethod> 
Public Function GetAllSpeakers(SubSite As String, MyUsername As String, MyPassword As String) As String 
    If ValidateUser(MyUsername, MyPassword) Then 

     If (HttpRuntime.Cache("CacheSpeakers") Is Nothing) Then 
      Try 
       Dim passWordEnc As SecureString = New SecureString() 
       For Each c As Char In Password.ToCharArray() 
        passWordEnc.AppendChar(c) 
       Next 

       Dim subContext As ClientContext = New ClientContext("url") 
       subContext.Credentials = New SharePointOnlineCredentials(Username, passWordEnc) 

       Dim json As String = JsonConvert.SerializeObject(LibraryMethods.Methods.GetSpeakers(subContext)) 


       HttpRuntime.Cache.Insert("CacheSpeakers", json, Nothing, 
       Cache.NoAbsoluteExpiration, New TimeSpan(0, 30, 0), 
       CacheItemPriority.NotRemovable, Nothing) 

       Return json 

      Catch ex As Exception 
       Return "ERROR: " & ex.InnerException.ToString 
      End Try 
     Else 
      Return HttpRuntime.Cache("CacheSpeakers").ToString() 
     End If 
    Else 
     Return "AUTHENTICATION FAILED" 
    End If 
End Function