2009-07-28 38 views
0

我正在爲所有控制器實現一個類來繼承,如果用戶未通過身份驗證,它將重定向到登錄頁面。 RedirectToAction行不會重定向。你能幫助正確嗎?MVC重定向問題

public class SecureController : Controller 
    { 
     public SecureController() 
     { 
      if (User == null || !User.Identity.IsAuthenticated) 
      { 
       RedirectToAction("Logon", "Account"); 
      } 
     } 
    } 

回答

1

我的建議是使用ActionFilter代替。它會容易得多。你可以做這樣的事情:

public class RequiresAuthenticationAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     // You can do any custom authentication logic in here 

     if (User == null || !User.Identity.IsAuthenticated) 
     { 
      // This assumes that Account is the controller, and Logon is the action method. 
      // You might want to check your routes if this is still not working correctly 
      RedirectToAction("Logon", "Account"); 
     } 
    } 
} 

這將讓那麼你只是把一個屬性上的操作方法,在你的控制器像這樣:

[RequiresAuthentication] 
public ActionResult Index() 
{ 
    return View(); 
} 

或者,正如其他人所指出的那樣,如果你不需要任何自定義的驗證邏輯,你可以只使用AuthorizeAttribute:

[Authorize] 
public ActionResult Index() 
{ 
    return View(); 
} 
+2

這已經內置見授權屬性 – terjetyl 2009-07-28 14:24:45