2013-09-05 17 views
0

當我登出使用此控制器:如何註銷以便在呈現頁面時不知道用戶已通過身份驗證?

public class LogOffController : Controller 
{ 
    public ActionResult Index() 
    { 
     FormsAuthentication.SignOut(); 
     return View(); 
    } 
} 

呈現的頁面不知道我已經登出,並在剃刀網頁的一部分,我顯示用戶:

@if (Request.IsAuthenticated) 
{ 
    <text>Welcome <strong>@Profile.GetPropertyValue("FullName")</strong> 
    @if (User.IsInRole("Administrator")) 
    { 
    @Html.ActionLink("(Administrator)", "Index", "Administration") 
    } 
    [ @Html.ActionLink("Log Off", "Index", "LogOff") ]</text> 
} 
else 
{ 
    @Html.ActionLink("Login", "Index", "Login") 
} 

這仍然顯示用戶名稱和管理員角色仍像登錄一樣。我瀏覽的下一頁是正確的。

回答

1

Dave Zych方法是一種比較喜歡的方式。但是,如果您想在原始問題中顯示LogOff View,則可以將null插入當前線程的主體對象。

public class LogOffController : Controller 
{ 
    public ActionResult Index() 
    { 
     FormsAuthentication.SignOut(); 

     HttpContext.User = null; 
     Thread.CurrentPrincipal = null; 

     return View(); 
    } 
} 
+0

謝謝,這是有效的,'HttpContext.User = null;'是唯一需要的行。任何使用Thread線的理由? – user2586804

+0

如果'Thread.CurrentPrincipal'不爲null,'Thread.CurrentPrincipal.Identity.IsAuthenticated'將爲true。如果你的代碼永遠不能訪問'Thread.CurrentPrincipal',你就沒事。但是,您可能也希望包含這一點,因爲如果下一位開發人員進入並使用'Thread.CurrentPrincipal',則會造成嚴重的安全漏洞。 – Win

1

代替返回視圖,請使用RedirectToActionRedirectToRoute

public class LogOffController : Controller 
{ 
    public ActionResult Index() 
    { 
     FormsAuthentication.SignOut(); 
     return RedirectToAction("Index", "MyController"); 
    } 
} 
+0

偉大的替代建議,我會用這個,但另一個答案回答瞭如何做到這一點,如果你需要的問題。 – user2586804

0

這是因爲HttpContext.User在ASP.NET管道從認證cookie讀取值時設置。當你做FormsAuthentication.SignOut(); - 你只是告訴瀏覽器刪除驗證cookie,但它對.NET當前用戶一無所知。 爲了解決這個問題,你有兩個選擇:

  • 重定向用戶到其他頁面,以便您的請求經過管道再次 和.NET知道,如果用戶進行身份驗證。
  • 手動註銷用戶:

    var currentUser = new GenericPrincipal(new GenericIdentity(string.Empty), null); 
    HttpContext.User = currentUser; 
    Thread.CurrentPrincipal = currentUser; 
    

    注意,你不應該分配null作爲當前用戶,因爲在視圖中,您可能會遇到一些財產的通話User,例如User.Identity.IsAuthenticated

相關問題