无法将类型 'System.Web.Hosting.SimpleWorkerRequest' 的对象转换为类型 'System.Web.Hosting.IIS7WorkerRequest'

Unable to cast object of type 'System.Web.Hosting.SimpleWorkerRequest' to type 'System.Web.Hosting.IIS7WorkerRequest'

我将我的解决方案从 VS2010 迁移到 VS2013 后收到 InvalidCastException。

在VS2010中一切正常,同样的代码在VS2013中出现如下错误:

An exception of type 'System.InvalidCastException' occurred in System.Web.dll but was not handled in user code

Additional information: Unable to cast object of type 'System.Web.Hosting.SimpleWorkerRequest' to type 'System.Web.Hosting.IIS7WorkerRequest'.

我不知道该怎么办,在互联网上找不到任何相关内容。

错误发生在以下代码的第 5 行:

public static void AuthenticateUser(String UserName, Int32 Minutes = 30, Boolean IsPersistent = true)
    {
        FormsAuthenticationTicket _ticket = new FormsAuthenticationTicket(1, UserName, DateTime.Now, DateTime.Now.AddMinutes(Minutes), IsPersistent, String.Empty);
        FormsIdentity _id = new FormsIdentity(_ticket);
        var _roles = Roles.GetRolesForUser(UserName);
        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(_id, _roles);
    }

你不能从一个兄弟 class 投射到另一个兄弟;您可以从 parent 转换为 child,或从 child 转换为 parent,但不能在兄弟姐妹之间转换。

https://msdn.microsoft.com/en-us/library/ms173105.aspx

由于 SimpleWorkerRequest 和 IIS7WorkerRequest 都继承自 HttpWorkerRequest,因此不能在它们之间转换。我首先会问自己为什么要或认为必须执行此转换,如果找不到替代方法,则编写一个转换方法来映射它们。但是,这通常是一个好兆头,表明您的代码走错了路。

从技术上讲,这不是答案。但它帮助我解决了我的问题。 因此,我将此与大家分享,希望这会在不久的将来避免让某些人头疼。

在 Visual Studio 2010 Professional 中,我 运行 我的项目使用 Visual Studio 使用特定端口 (4302) 的开发服务器。

在 Visual Studio 2013 社区版中,我是 运行 我在 IIS Express 上的项目。 出于某种原因,我仍然不知道为什么,这导致我的软件将 'IIS7WorkerRequest' 转换为 'SimpleWorkerRequest' 对象。

在我切换到具有自定义虚拟目录的本地 IIS 服务器后,我的错误消失了。如果有人可以解释这一点,我很想知道为什么会这样。但是现在这解决了上面的问题。