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

938 views Asked by At

I am getting an InvalidCastException after I migrated my solution from VS2010 to VS2013.

In VS2010 everything works fine, the same code gives the following error in 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'.

I don't know what to do, couldn't find anything related on the internet.

The error occurs on line 5 in the following piece of code:

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);
    }
2

There are 2 answers

0
Robin Gordijn On BEST ANSWER

Technically, this is not an answer. But it helped me fix my problem. Therefore I am sharing this with you all, hopefully this will prevent some headache for somebody in the near future.

In Visual Studio 2010 Professional I was running my project using the Visual Studio Development Server using a Specific Port (4302).

In Visual Studio 2013 Community edition i was running my project on IIS Express. For some reason, I still do not know why, this caused my software to cast a 'IIS7WorkerRequest' to a 'SimpleWorkerRequest' object.

After I switched to the Local IIS Server with a custom virtual directory my error was gone. If there is somebody who can explain this, I would love to know why this is happening. But for now this fixed the problem above.

5
Marisa On

You cannot cast from a sibling class to another sibling; you can cast from parent to child, or child to parent, but not between siblings.

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

Since both SimpleWorkerRequest and IIS7WorkerRequest inherit from HttpWorkerRequest, you cannot cast between them. I would first ask yourself why you want to or think you have to perform this conversion, and if you cannot find an alternative then write a conversion method to map between them. However, this is usually a good sign that you're headed down the wrong path for your code.