在Asp.net MVC 5应用程序中,我通过模型将SecureString传递到我的视图中。我现在想将SecureString的内容写入Response流,而不必先将其转换为字符串。我怎样才能做到这一点?
答案 0 :(得分:1)
这是我提出的HtmlHelper扩展。我确信它可以改进,但它实现了我的目标,即将SecureString写入Response流,而不会将其表示为字符串。
public static class SecureStringHelpers
{
public static void WriteSecureStringToResponse(this HtmlHelper helper, SecureString secureString)
{
if (secureString != null)
{
IntPtr unmanagedString = IntPtr.Zero;
var secureByteArray = new byte[2];
try
{
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
var offset = 0;
var endOfString = false;
do
{
secureByteArray[0] = Marshal.ReadByte(unmanagedString, offset);
offset++;
secureByteArray[1] = Marshal.ReadByte(unmanagedString, offset);
offset++;
if (!(secureByteArray[0] == 0 && secureByteArray[1] == 0))
{
helper.ViewContext.Writer.Write(System.BitConverter.ToChar(secureByteArray, 0));
}
else
{
endOfString = true;
}
} while (!endOfString);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
secureByteArray[0] = 0;
secureByteArray[1] = 0;
}
}
}
}