2012-08-06 193 views
9

无论何时尝试构建,我都会收到此错误。我刚安装了Visual Studio 2012和.NET 4.5,但这个项目仍然是在2010年无法将类型为'System.Int32'的对象转换为类型'System.Web.Security.Cryptography.Purpose'

这里是我有问题的代码行:

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

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

我发现an article有关Sitecore有这个错误,但这是我见过它弹出的唯一的地方。

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

他们的解决方案是:

  • 卸载VS11如果您有它安装
  • 卸载.NET 4.5
  • 重新安装.NET 4

这似乎是一个荒谬溶液吨帽子4.5和4不能放在同一台机器上。

有没有人知道什么可能导致这个和任何更好的解决方案之前我尝试卸载并重新安装一堆东西?

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

+0

很难真正知道你所提供的是怎么回事。即你没有发布实际使用类型Purpose的东西。你试图调用什么方法? – 2012-08-06 15:56:25

+0

对不起,我已经添加了我在这里打电话的地方。这是足够的信息吗? – JCisar 2012-08-06 16:12:00

+0

我没有看到您的编辑与您最初发布的代码有关,并表示存在“问题”。你正在使用什么'HttpSecureCookie'类? – 2012-08-06 16:15:58

回答

9

正如@hvd所暗示的,这段代码使用了反射来调用微软在.NET 4.5中改变的内部方法。

幸运的.NET 4.0中引入的System.Web.Security.MachineKey类公共Encode()Decode()方法可完成基本上同样的事情,在CookieProtectionHelper内部方法。请注意,使用CookieProtectionHelper.Encode()加密的cookie将无法使用MachineKey.Decode()进行解密。

另请注意,在.NET 4.5中,这些方法已弃用,因此推荐使用Protect()Unprotect()

+1

谢谢你这篇文章!你为我提供了一个很好的解决方案,而不是我拥有的东西。我会试试这些! – JCisar 2012-08-21 20:27:04

+1

用MachineKey.Encode()和Decode()替换CookieProtectionHelper为我工作。我使用4.0,但最近安装了4.5,导致这种情况发生。 – Induster 2013-12-02 18:59:42

3

你从here得到了吗?

_encode = cookieProtectionHelper.GetMethod(
    "Encode", BindingFlags.NonPublic | BindingFlags.Static); 

这依赖于MS从未承诺过的.NET Framework的内部实现细节保持不变。所以是的,.NET框架的就地升级很可能会使这种代码停止工作。这不是.NET 4.5中的一个错误。这是你的代码 - 依赖于你不能依赖的东西的代码。

并解决它,停止使用该方法。如果有一个公共API可以实现你想要的功能,那就使用它。如果没有,请自行实施。

+0

我不知道代码来自哪里......它在我开始为这家公司工作之前就在这里。 – JCisar 2012-08-06 16:54:22

+0

无论哪种方式,如果这就是你的'_encode'设置的,你真的需要抛弃它。您的代码不会因官方发布的.NET版本而失败,但很快就会发生。 – hvd 2012-08-06 17:03:03

+0

它说新版本会贬低它呢? – JCisar 2012-08-07 16:44:13

1

如果您看到这个错误,而使用CMS软件Ektron,以下是他们的8.7 release notes -

71233—If you installed an 8.6.1 site and enabled cookie encryption in web.config(), then installed Microsoft .NET Framework 4.5, you saw this error:

Server Error in '/' Application. 
Object of type 'System.Int32' cannot be converted to type System.Web.Security.Cryptography.Purpose'. This 

is fixed.

正如其他答案中提到的,一种解决方案是回滚到.Net框架奥克4.0。 Ektron在这个特殊情况下的其他答案是禁用cookie加密,或者升级到8.7。

+0

谢谢海绵宝宝!你为我节省了一天的工作。 – eastboundr 2013-06-10 14:20:45

相关问题