2013-03-17 60 views
1

我設置下面Context.User.Identity.Name在MVC返回null 4

FormsAuthentication.SetAuthCookie("test", true);

這樣的窗體身份驗證cookie,當我檢查,如果其設定返回null ...

Context.User.Identity.Name 

任何想法爲什麼會發生這種情況?感謝

+0

你在哪裏打電話? – 2013-03-17 13:31:27

+0

我設置了「FormsAuthentication.SetAuthCookie(」test「,true);」在控制器中並從Layout.cshtml(主頁) – 2013-03-17 13:37:56

+0

調用「Context.User.Identity.Name」他們是否在同一個請求? – 2013-03-17 13:38:26

回答

3

你應該設置窗體身份驗證cookie後總是重定向:

public ActionResult SomeAction() 
{ 
    FormsAuthentication.SetAuthCookie("test", true);  
    return RedirectToAction("FooBar"); 
} 

這只是在隨後的行動要重定向到您將得到User.Identity.Name被正確初始化。原因很簡單:User.Identity.Name屬性從請求cookie(aka傳入的cookie)初始化,而FormsAuthentication.SetAuthCookie將表單認證設置爲響應(也就是發出cookie),以便在隨後的請求中將此cookie發送請求。

+0

是啊這就是我正在做的..看到下面的答案 – 2013-03-17 14:16:05

+0

好吧,在'首頁/索引'行動,你應該能夠成功檢索User.Identity.Name'。確保你的web.config中已經正確配置了表單身份驗證,並且在瀏覽器中啓用了cookie: /認證>'。 – 2013-03-17 14:16:48

+0

那就是我錯過了web.config配置..感謝很多隊友! – 2013-03-17 14:23:42