我有一个 WCF 服务,它在以后的不确定时间代表用户排队和执行命令。我希望将 WindowsIdentity 存储为字节数组并将其填充到数据库中,然后反序列化并使用该对象。
有时,服务按预期执行:它以用户身份正确序列化、存储、反序列化和执行命令。其他时候,我在反序列化 WindowsIdentity 时收到错误“调用的目标已引发异常”,还有其他时候反序列化有效,但在执行命令的过程中,标识不再有效。
我的问题是:在 .NET 4.0 框架中,是否可以在没有明确用户名和密码的情况下使用 WCF 在稍后的不确定时间代表用户执行命令?
我正在使用的代码如下:
序列化:
''' <summary>
''' Serializes a WindowsIdentity as a binary encoded byte array.
''' </summary>
''' <param name="identity">The identity to serialize.</param>
''' <returns>A byte array containing a binary representation of the identity.</returns>
Private Function SerializeWindowsIdentity(ByVal identity As WindowsIdentity) As Byte()
If IsNothing(identity) Then Return Nothing
Try
Dim bf As New BinaryFormatter
Using ms As New MemoryStream()
bf.Serialize(ms, identity)
Return ms.ToArray()
End Using
Catch ex As Exception
Return Nothing
End Try
End Function ' SerializeWindowsIdentity
反序列化:
''' <summary>
''' Deserializes a WindowsIdentity from a binary encoded byte array.
''' </summary>
''' <param name="identity">A byte array containing a binary representation of a WindowsIdentity</param>
''' <returns>The deserialized WindowsIdentity from the byte array.</returns>
Private Function DeserializeWindowsIdentity(ByVal identity As Byte()) As WindowsIdentity
If IsNothing(identity) OrElse identity.Count = 0 Then Return Nothing
Try
Dim bf As New BinaryFormatter()
Using ms As New MemoryStream(identity)
Dim obj As Object = bf.Deserialize(ms)
Return CType(obj, WindowsIdentity)
End Using
Catch ex As Exception
Return Nothing
End Try
End Function ' DeserializeWindowsIdentity
WindowsIdentity 捕获:
identity = SerializeWindowsIdentity(ServiceSecurityContext.Current.WindowsIdentity)
用法:
Dim cxt As WindowsImpersonationContext
Try
Dim wi As WindowsIdentity = DeserializeWindowsIdentity(identity)
If Not IsNothing(wi) Then cxt = wi.Impersonate()
' Do Stuff
Finally
If Not IsNothing(cxt) Then cxt.Dispose()
End If