Unable to cast object of type 'System.Security.Principal.GenericIdentity' to type 'System.Web.Security.FormsIdentity'

29.2k views Asked by At

I have get this error during the site log in.How can i resolve this problem.enter image description here

4

There are 4 answers

2
Wiktor Zychla On

Apparently the principal object associated with current request was GenericIdentity rather than FormsIdentity. 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 the IsAuthenticated to false. I'd rewrite the code to:

 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
 }
3
James 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;
0
user4960676 On

This problem occurs when the user is not authenticated: either you removed cookies from your browser and again you're accessing the URL directly without login.

1
Peter Henry 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; 

}