2013-10-27 18 views
2

登錄後,下面是用於登錄MVC WebSecurity.CurrentUserName空CurrentUserID -1用戶

WebSecurity.Login("abc", "123", true);//return true 
return RedirectToAction("afterLogin", @"afterLogin"); 

洛在之後的代碼,我檢查了用戶的ID,看它是否通過運行的-1下面一行:

WebSecurity.CurrentUserId 

但爲什麼每當我叫這個,返回值始終爲-1和CurrentUserName是空的?

編輯:

另外一個問題:

是否WebSecurity有類似的超時,這樣一個特定時期,並將在用戶空閒自動退出?

+0

可能重複的 - 爲什麼WebSecurity.CurrentUserId -1登錄後](http://stackoverflow.com/questions/13850861/mvc-4-simplemembership-why-websecurity-currentuserid-1-after-login) – Yogesh

+0

我試過解決方案之前,該鏈接,我已重定向到另一個頁面,但結果仍然相同。 – User2012384

+0

你應該把它分成兩個不同的問題。 –

回答

1

我認爲瀏覽器會話結束時,默認的過期是。這可能是因爲cookies沒有啓用,這就是爲什麼它返回-1需要啓用cookie。

+0

我檢查了開發者工具,發現裏面有一個名爲「AUTH」的cookie,並且有它的價值。 – User2012384

+0

很奇怪,我不知道那是怎麼回事。您可能想要在Visual Studio中調試您的網站。 – 2013-11-02 10:20:30

+0

我需要「重定向到」另一個頁面才能使cookie生效嗎?或者我可以舉一個關於如何使用WebSecurity.CurrentUserName函數的例子。 – User2012384

3

檢查webconfig,您必須啓用窗體身份驗證:

添加以下代碼段內

<authentication mode="Forms"> 
     <forms loginUrl="~/Account/Login" timeout="3600" /> 
    </authentication> 

評論,如果它是在你的webconfig:

<!--<modules> 
     <remove name="FormsAuthentication" /> 
</modules>--> 

現在可以檢查

WebSecurity.CurrentUserName,WebSecurity.CurrentUserId和,WebSecurity.IsAuthenticated標誌;

而且在app_start

public static class AuthConfig 
    { 
     public static void RegisterAuth() 
     { 
} 
} 

添加這個類,並在Global.asax.cs中稱這種現象AppStart的

AuthConfig.RegisterAuth(); 
[MVC 4 SimpleMembership的