I have get this error during the site log in.How can i resolve this problem.
Unable to cast object of type 'System.Security.Principal.GenericIdentity' to type 'System.Web.Security.FormsIdentity'
29.2k views Asked by user1939371 At
4
There are 4 answers
3
On
The exception tells you everything you need to know here, FormsIdentity
cannot be cast to GenericIdentity
because they are 2 completely different classes.
You don't really provide any sort of information as to why you are casting, however, the common base class between both those types is ClaimsIdentity e.g.
var identity = (ClaimsIdentity)HttpContext.Current.User.Identity;
1
On
I ran into this problem because I had forgotten to use the [Authorize]
attribute on an entry point to my web app that was using forms authentication. The entry point tried to cast User.Identity
from a GenericIdentity
to a FormsIdentity
and failed.
In my ASP.NET MVC Controller I had the following code;
public ActionResult Index(long? eventID)
{
// error occurred here
FormsIdentity id = (FormsIdentity)HttpContext.User.Identity;
}
Changed to this enforced the authentication method set in my web.config;
<authentication mode="Forms">
Updated code;
[Authorize]
public ActionResult Index(long? eventID) {
FormsIdentity id = (FormsIdentity)HttpContext.User.Identity;
}
Apparently the principal object associated with current request was
GenericIdentity
rather thanFormsIdentity
. Casting between these two is not possible.You should carefully inspect your application's stack with respect to identity management modules and all other possible places in your code where the identity is set for current request. If you are able to identify the culprit that sets the
GenericIdentity
- you are done, you could rewrite/redesign this particular spot.My guess is that this problem occurs when the user is not authenticated. The runtime creates a
GenericIdentity
for current request and sets theIsAuthenticated
tofalse
. I'd rewrite the code to: