Another Invalid Cast exception

Another Invalid Cast exception

Old forum URL: forums.lhotka.net/forums/t/4605.aspx


HarryOffutt posted on Wednesday, April 02, 2008

 I've included a code snippet below, from my problem area in regard to improper casting... I didn't write this code, I inherited it, so I'm trying to understand why it's breaking.  At the "RedirectFromLoginPage" that redirect jumps to a new thread.  In that thread(page redirected to), how do I reference or access the "Csla.ApplicationContext.User"

The cast exception occurs because while I am in context of the login page, the identity is a{nfrc.cpms.security.CPMSIdentity} System.Security.Principal.IIdentity

When the thread context changes to the default page after the redirect, it changes to:

Csla.ApplicationContext.User.Identity {System.Web.Security.FormsIdentity} System.Security.Principal.IIdentity {System.Web.Security.FormsIdentity}

How do I reference the "real" principle identity and broker when the page changes?  Basically, at the point the new page starts loading, the watch on the User now says "The name 'User' does not exist in the current context"

Thanks!



------------------------------------------------------
I clipped out code not relevent to the question...

Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
' Purpose:
' Authenticate user.
.
.
.

If CPMSSecurityBroker.Login(txtUsername.Text, txtPassword.Text, ddlProgram.SelectedValue, changePassword) Then
   ' Set custom principal. It will be retrieved automatically w/ every page call. see Global.asax
   CPMSWeb.Principal = Csla.ApplicationContext.User

   If CPMSUser.IsAdmin Then
      bDoLogin = True
   End If

   If bDoLogin Then
     FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, cbRememberMe.Checked)
   End If

End If

If Not bDoLogin Then
   ' Reset to an unauthenticated principal
   CPMSWeb.LogOut()
   lblBadLogin.Text = FAILED_LOGIN_MSG
End If

End Sub

cliffordru replied on Wednesday, April 02, 2008

It is a little tough to determine from this code, but part of the login or membership provider should be setting the Csla.ApplicationContext.User .  This needs to be persisted however, otherwise the identity will go back to the FormsIdentity, not the custom Csla Identity.  One approach outlined in Rocky's book is to persist the Csla Principal in session and use the event handler Application_AcquireRequestState in the global.asax to to ensure the Csla.ApplicationContext.User always has a value for authenticated users.

You also need to explicitly cast the Csla.ApplicationContext.User.Identity to the custom type you are using in your application (if you are using a custom identity inheriting from Csla.BusinessBase<CustomIdentity>, IIdentity)

Hope that helps

Copyright (c) Marimer LLC