2011-07-21 34 views
15

我是ASP.NET新手,我試圖找到一種方法來輕鬆地將未經身份驗證的用戶從網站上的任何頁面重定向到登錄頁面。如果還有其他選項,我寧願不要在每個HTTP GET函數中放入以下代碼。如何在MVC 3中未經身份驗證輕鬆重定向?

if (!Request.IsAuthenticated) 
{ 
    return RedirectToAction("LogOn", "Account"); 
} 

回答

12

您可以將[Authorize]屬性置於需要驗證的每個操作上。

此外,確保這部分在web.config中定義:

<authentication mode="Forms"> 
    <forms loginUrl="~/Account/LogOn" timeout="2880" /> 
</authentication> 
+1

完全正確,只是澄清 - 這個配置部分應放在在「system.web」中。 – tltjr

3

看我只是嘗試這樣做:

<!-- using custom auth with MVC redirect --> 
<authentication mode="None"> 
    <forms loginUrl="~/Home/Index"/> 
</authentication> 

,它仍然有效,雖然我使用自定義的身份驗證。雖然不知道超時 - 將[授權]仍然使用默認的表單身份驗證或它根本不會管理超時(自定義身份驗證的首選行爲)。

0

我使用了下面的代碼片段,發現它非常優雅,不需要編寫任何重定向語句。 MVC需要基於表單登錄頁面配置,且在全成登錄/註冊,用戶被髮送回最初請求的頁面重定向的護理

if (!User.Identity.IsAuthenticated) 
{ 
    //return new HttpUnauthorizedResult(); //This or the below statement should redirect the user to forms login page 
    return new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized); 
} 
相關問題