"System.Int32"类型的对象无法转换为"System.Web.Security.Cryptography.Purpose"类型

JCi*_*sar 9 c# exception-handling asp.net-4.5

每当我尝试构建时,我都会收到此错误.我刚刚安装了Visual Studio 2012和.Net 4.5,但这个项目仍然在2010年.

以下是我遇到问题的代码行:

private static MethodInfo _encode;
public static string Encode(CookieProtection cookieProtection, byte[] buf, int count)
{
  return (string)_encode.Invoke(null, new object[] { cookieProtection, buf, count });
}
Run Code Online (Sandbox Code Playgroud)

我收到一条ArgumentException was unhandled by user code错误消息,说"Object of type 'System.Int32' cannot be converted to type 'System.Web.Security.Cryptography.Purpose'" 我的开发环境没有任何变化,我的同事没有遇到同样的问题,但他们也没有VS2012.

我发现一篇关于Sitecore 的文章有这个错误,但这是我见过的唯一一个弹出的地方.

他们在那里说,"这是因为在.NET 4.5中,System.Web中有一些新的命名空间"

他们的解决方案是:

  • 如果安装了VS11,请将其卸载
  • 卸载.NET 4.5
  • 重新安装.NET 4

这似乎是一个荒谬的解决方案,4.5和4不能在同一台机器上.

在我尝试卸载并重新安装一堆东西之前,是否有人知道可能导致此问题以及任何更好的解决方案?

评论也说尝试:</setting name="login.rememberlastloggedinusername" value="false" >但我也不想这样做.

sec*_*ean 9

正如@hvd所提到的,这段代码使用反射来调用Microsoft在.NET 4.5中更改的内部方法.

幸运的是,.NET 4.0引入了System.Web.Security.MachineKey带有public Encode()Decode()方法的类,它实现了与内部方法基本相同的功能CookieProtectionHelper.请注意,使用加密的cookie CookieProtectionHelper.Encode()将无法解密MachineKey.Decode().

另请注意,在.NET 4.5中,这些方法不赞成使用Protect()Unprotect().


Jbo*_*aga 7

在web.config中将值更改为false:

<setting name=”Login.RememberLastLoggedInUserName” value=”false” /> 
Run Code Online (Sandbox Code Playgroud)

(来自:http://truncatedcodr.wordpress.com/2012/06/20/fix-sitecore-and-net-framework-4-5/)