2016-11-07 30 views
1

我一直在環顧四周,找不到我想要的東西,或者它比我想象的更復雜,這就是爲什麼我要問。如果會話對象爲空,MVC強制註銷

就像我在我的_LoginPartial.cshtml看到:

@if (Request.IsAuthenticated) 
{ 
     @try 
     { 
      <li> 
       <a>@Html.Label("Hello " + Session["username"].ToString() + " !")</a> 
      </li> 
      <li><a href="javascript:document.getElementById('logoutForm').submit()">Disconnect</a></li> 

     } 
     catch (NullReferenceException) 
     { 

     <li>@Html.ActionLink("Connect", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> 
     } 
} 
else 
{ 
     <li>@Html.ActionLink("Connect", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> 
} 

有時候,MVC計算,而在現實中,我的會話是完全地空@if (Request.IsAuthenticated)是真實的。

有沒有辦法鏈接MVC身份驗證與會話對象或至少,如果session["username"]是空的強制退出?

+0

類似的問題:http://stackoverflow.com/questions/23209961/why-request-isauthenticated-return-true-but-session-is-null – AndreFeijo

+0

所以我可以完全忽略resquest.Authentication,只使用會話對象爲我的需要 –

+0

會話與認證無關 - Request.IsAuthenticated僅查看當前線程是否有一個Principle對象。你如何驗證你的用戶? –

回答

-1

我不知道爲什麼我不能把它earlyer:

@if (Session["username"] != null) 
{ 
    <li> 
      <a>@Html.Label("Hello " + Session["username"].ToString() + " !")</a> 
    </li> 
    <li><a href="javascript:document.getElementById('logoutForm').submit()">Disconnect</a></li> 
} 
else 
{ 
    <li>@Html.ActionLink("Connect", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> 
} 

只需卸下Request.IsAuthenticated並直接使用session對象,如果是空的,你不希望鬼用戶(空會話用戶)能夠在該網站周圍走動。