2017-03-16 58 views
1

我已經添加了一個哈希函數到我現有的代碼(一個基本的登錄頁面),期待返回一個字符串。下面是函數:InvalidCastException當調用哈希函數

Public Shared Function sha256_hash(value As [String]) As [String] 
    Using hash As SHA256 = SHA256Managed.Create() 
     Return [String].Join("", hash.ComputeHash(Encoding.UTF8.GetBytes(value)).[Select](Function(item) item.ToString("x2"))) 
    End Using 
End Function 

當我嘗試登錄我得到以下excepton:

InvalidCastException的:無法投類型WhereSelectArrayIterator`2的」對象[System.Byte,System.String ]'鍵入'System.String []'。

我試圖尋找解決方案,但什麼也沒找到。我沒有經驗與vb.net所以幫助表示讚賞。

編輯: 此功能似乎在本地主機上正常工作,但發佈到Web服務器時,它崩潰。它可能是一個框架問題嗎?

+0

該代碼爲我工作。你怎麼調用這個函數? – Pikoh

+0

也適用於我。 – Misery

+1

['String.Join (string,IEnumerable )'](https://msdn.microsoft.com/en-us/library/dd992421(v = vs.110).aspx)是一個新增加的重載。 NET 4.0。 –

回答

2

我可以重現你的情況使用.NET 3.5,作爲Damien_The_Unbeliever說,不包含String.Join<T>(string,IEnumerable<T>)String.Join期待的StringSelect數組並返回一個IEnumerable(Of T)

雖這麼說,你需要通過以下

Public Shared Function sha256_hash(value As [String]) As [String] 
    Using hash As SHA256 = SHA256Managed.Create() 
     Return [String].Join("", hash.ComputeHash(Encoding.UTF8.GetBytes(value)).[Select](Function(item) item.ToString("x2")).ToArray()) 
    End Using 
End Function 

改變你的代碼,使其運行在.NET 2.0中的你問,你需要刪除你的Select聲明,因爲它是在.NET 3.5中引入的,而不是使用Select,你可以簡單地對由.ComputeHash返回的數組進行foreach,如下所示。

Public Shared Function sha256_hash(value As [String]) As [String] 
    Using hash As SHA256 = SHA256Managed.Create() 
     Dim hashString = String.Empty 
     Dim computedHash = hash.ComputeHash(Encoding.UTF8.GetBytes(value)) 
     For Each item In computedHash 
      hashString = String.Concat(hashString, item.ToString("x2")) 
     Next 
     Return hashString 
    End Using 
End Function 

希望這有助於

+0

函數是否可以在框架2中工作?如果沒有,我可以改變什麼來使它工作? –

+0

我編輯了我的答案來回答這個問題 – Misery