我在网站登录期间收到此错误。我该如何解决此问题。
4 回答
显然,与当前请求关联的主体对象是GenericIdentity
而不是FormsIdentity
. 这两者之间的转换是不可能的。
您应该仔细检查您的应用程序堆栈中的身份管理模块以及代码中为当前请求设置身份的所有其他可能位置。如果您能够确定设置的罪魁祸首GenericIdentity
-您已经完成,您可以重写/重新设计这个特定的位置。
我的猜测是当用户未通过身份验证时会出现此问题。GenericIdentity
运行时为当前请求创建一个并将其设置IsAuthenticated
为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
}
异常告诉你这里需要知道的一切,因为它们是 2 个完全不同的类,FormsIdentity
所以不能转换为。GenericIdentity
你并没有真正提供任何关于你为什么要强制转换的信息,但是,这两种类型之间的公共基类是ClaimsIdentity例如
var identity = (ClaimsIdentity)HttpContext.Current.User.Identity;
我遇到了这个问题,因为我忘记在[Authorize]
使用表单身份验证的 Web 应用程序的入口点上使用该属性。入口点尝试User.Identity
从 aGenericIdentity
转换为 aFormsIdentity
并失败。
在我的 ASP.NET MVC 控制器中,我有以下代码;
public ActionResult Index(long? eventID)
{
// error occurred here
FormsIdentity id = (FormsIdentity)HttpContext.User.Identity;
}
更改为强制执行我的 web.config 中设置的身份验证方法;
<authentication mode="Forms">
更新代码;
[Authorize]
public ActionResult Index(long? eventID) {
FormsIdentity id = (FormsIdentity)HttpContext.User.Identity;
}
当用户未通过身份验证时会出现此问题:您从浏览器中删除了 cookie,并且您再次直接访问 URL 而无需登录。