InvalidCastException occurs when the conversion of an instance type to another is not supported. For example, if you try to convert a Char type to DateTime, it will result in InvalidCastException.
For an application I troubleshoot, this was the stack trace of the error:
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.InvalidCastException: [A]ASP.common_master cannot be cast to [B]ASP.common_master. Type A originates from 'App_Web_2th3e42t, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'D:\local\Temporary ASP.NET Files\root\dfgdf\3gdfgdf\App_Web_2th3rt2t.dll'. Type B originates from 'App_Web_grzmaoii, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'D:\local\Temporary ASP.NET Files\root\dfgdf\3gdfgdf\App_Web_grzmaoii.dll'.
at ASP.login_index_aspx.get_Master()
at ASP.login_index_aspx.__RenderclpJSscript(HtmlTextWriter __w, Control parameterContainer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at ASP.zh_include_common_master.__RenderbodyNode(HtmlTextWriter __w, Control parameterContainer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
Solution
Review your code to find out what conversions are being made and which one might be causing the exception. If the problematic conversion is not easy to find, set up automatic dump collection to create a dump file at the time this exception is thrown. The dump file should tell what the values were when the cast exception occurred.
In some rare cases, InvalidCastException might be solved by
- Deleting the temporary ASP.NET compiled folder after compilation
- Using a different DLL file for the each user control
- Using staging slot to deploy code and swapping into production slot
- Removing circular dependencies in user controls