2011-05-23 77 views
1

我有幾個鏈接(登錄,註銷和註冊)在_layout模板,這裏的鏈接取決於用戶是否登錄顯示像這樣:MVC3剃刀引擎執行/渲染順序

if (User.Identity.IsAuthenticated) 
{ 
    <span class="username">@User.Identity.Name</span> 
    <span class="link">@Html.ActionLink("Logout", "Logout", "Account")</span> 
} 
else 
{ 
    <span class="link">@Html.ActionLink("Login", "Login", "Account")</span> 
    <span class="link">@Html.ActionLink("Register", "Register", "Account")</span> 
} 

問題是,註銷鏈接在用戶首次退出系統時仍然顯示(我希望立即替換爲登錄並註冊鏈接) - 即直到頁面刷新,或者用戶移到另一頁面。這裏是註銷操作代碼:

public ActionResult Logout() 
{ 
    FormsAuthentication.SignOut(); 
    Session.Abandon(); 

    return View(); 
} 

我已經通過這個環節了 - http://mvcdev.com/differences-between-asp-net-razor-and-web-forms-view-engines/ - 這也解釋了剃刀引擎的執行順序,但對我來說這似乎是執行不同。理想情況下,我希望FormsAuthentication.SignOut()在_layout中的User.Identity.IsAuthenticated之前執行。

我在做什麼錯?謝謝!

回答

3

這是正常的,你需要註銷後重定向:

public ActionResult Logout() 
{ 
    FormsAuthentication.SignOut(); 
    Session.Abandon(); 

    return RedirectToAction("Index"); 
} 

之所以出現這種情況是因爲當客戶端請求他還在驗證註銷鏈接(他發來的驗證cookie隨着請求) 。然後在控制器操作中,您將其註銷(FormsAuthentication.SignOut()),該操作只不過是在後續的請求上標記要刪除的身份驗證Cookie。然後你返回一個視圖,當然這個視圖裏面的用戶仍然被認證,因爲這個視圖在相同的請求下執行,並且cookie仍然存在。

+0

謝謝Darin!我不認爲這會很簡單! – tathagata 2011-05-23 06:47:53