2013-02-05 103 views
1

我知道這裏有幾個問題已經存在,但沒有人似乎幫助我的問題。.NET 4.0 FormsAuthentication.SetAuthCookie失敗

我正在調試VB.NET webForms應用程序,我無法獲取FormsAuthentication.SetAuthCookie(使用非持久性cookie)工作。它似乎創建了一個HttpContext.Current.User對象,當我在監視窗口中檢查它時,它似乎創建了該對象,但不是它的「標識」屬性。

我讀過一堆SO帖子檢查了基本的東西,比如看我的瀏覽器是否支持cookies等等......這個項目是我們早期項目的一個直接端口,它使用相同的代碼這裏列出的東西,相對而言,它工作得很好。在拋出異常的地方,它是從我應該得到它的BLL代碼中調用的。

這裏是調用FormsAuthentication方法的代碼...:

'When participant logs in having already created records in DB. 
Protected Sub btnGo_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnGo.Click 
    If Me.txtUsername.Text.Trim.Length <> 0 AndAlso Me.txtPassword.Text.Trim.Length <> 0 Then 
     If Membership.ValidateUser(Me.txtUsername.Text, Me.txtPassword.Text) Then 
      FormsAuthentication.SetAuthCookie(Me.txtUsername.Text, False) 

      'This is where we run into trouble; the property checks with the forms auth... 
      MyBLL.Common.CurrentUser = New MyBLL.User(Me.txtUsername.Text) 

      'set site property.. 
      If Site_ IsNot Nothing Then 
       MyBLL.Common.CurrentUser.Site = Me.Site_ 
      End If 
      MyBLL.Common.CurrentParticpant = Nothing 
      MyBLL.Common.CurrentParticpantVisitID = -1 
      Response.Redirect("~/Apps/Dashboard.aspx", True) 
     Else 
      Me.lblLoginMsg.Visible = True 
     End If 
    Else 
     Me.lblLoginMsg.Visible = True 
    End If 
End Sub 

下面是BLL對象的代碼(其具有共享屬性主叫用戶從HttpContext的...)

 Public Shared Property CurrentUser() As MyBLL.User 
     Get 
      Dim objUser As MyBLL.User 

      If Not IsNothing(HttpContext.Current.Session("currentSiteUser")) Then 
       objUser = CType(HttpContext.Current.Session("currentSiteUser"), MyBLL.User) 
       If objUser.Username <> HttpContext.Current.User.Identity.Name Then 
        objUser = New MyBLL.User(HttpContext.Current.User.Identity.Name) 
        HttpContext.Current.Session("currentSiteUser") = objUser 
       End If 
      Else 
       objUser = New MyBLL.User(HttpContext.Current.User.Identity.Name) 
       HttpContext.Current.Session("currentSiteUser") = objUser 
      End If 

      Return objUser 

     End Get 
     Set(ByVal value As MyBLL.User) 
      '_CurrentUser = value 
      HttpContext.Current.Session("currentSiteUser") = value 
     End Set 
    End Property 

這是我的webConfig中的Forms元素;一切似乎好到我這裏來......

<authentication mode="Forms"> 
     <forms loginUrl="~/Public/Default2.aspx" defaultUrl="~/Public/Default2.aspx" timeout="60"/> 
    </authentication> 

回答

5

你應該callaing的SetAuthCookie方法,只有在後續請求可能希望獲得完整的IPrincipal後立即重定向進行初始化。不要試圖在與SetAuthCookie方法相同的控制器操作中訪問HttpContext.Current.User.Identity.Name。它不會有任何效果。重定向很重要,以便在下一次請求時,表單身份驗證模塊將從請求cookie構建主體。

在您的CurrentUser方法中,您似乎在調用HttpContext.Current.User.Identity.Name屬性,但直到重定向後纔可用。

+0

謝謝!有效。仍然不明白爲什麼它在代碼的起源遺留應用程序的工作,但這是另一天的另一場戰鬥... – lewiSnort

相關問題