Wik*_*hla 10

显然,与当前请求相关联的主要对象GenericIdentity不是FormsIdentity.这两者之间的铸造是不可能的.

您应该仔细检查应用程序的堆栈,包括身份管理模块和代码中为当前请求设置标识的所有其他可能位置.如果你能够确定设置的罪魁祸首GenericIdentity- 你已经完成了,你可以重写/重新设计这个特定的位置.

我的猜测是,当用户未经过身份验证时会出现此问题.运行时创建GenericIdentityfor当前请求并设置IsAuthenticatedto false.我将代码重写为:

 if ( HttpContext.Current.User != null && HttpContext.Current.User.Identity is FormsIdentity )
 {
    // your code follows
 }
 else
 {
    // the user is not yet authenticated and 
    // there is no Forms Identity for current request
 }
Run Code Online (Sandbox Code Playgroud)