2016-03-13 210 views
0

ASP.NET MVC RedirectResult類我有簡單的自定義驗證過濾器:使用自定義驗證過濾器

public class MyAuthAttribute : FilterAttribute, IAuthenticationFilter 
{ 

    public void OnAuthentication(AuthenticationContext filterContext) 
    { 
     filterContext.Result = new RedirectResult("Account/Login"); 
    } 

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) 
    { 
     //throw new NotImplementedException(); 
    } 
} 

還有的HomeController與Index操作方法和使用的AccountController登錄操作方法。索引操作方法使用我的自定義過濾器。當我嘗試調用索引操作方法時,我的過濾器攔截代碼執行並重定向到主頁/帳戶/登錄URL。爲什麼會發生?我期望在AccountController中調用Login操作。

回答

0

您正在重定向,因爲您的篩選器中沒有條件可確保用戶在重定向之前未通過身份驗證。

過濾器運行請求。您需要在過濾器中放入分支邏輯以使其具有條件。

public class MyAuthAttribute : FilterAttribute, IAuthenticationFilter 
{ 

    public void OnAuthentication(AuthenticationContext filterContext) 
    { 
     if (!filterContext.Principal.Identity.IsAuthenticated) 
      filterContext.Result = new RedirectResult("Account/Login"); 
    } 

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) 
    { 
     //throw new NotImplementedException(); 
    } 
} 

參考:http://jameschambers.com/2013/11/working-with-iauthenticationfilter-in-the-mvc-5-framework/

+0

的解決方案是很簡單的。當我們指定url時,需要添加「/」或「〜/」。條件不影響代碼執行。 – lam3r