簡體   English   中英

在自定義身份驗證篩選器中使用ASP.NET MVC RedirectResult類

[英]Using ASP.NET MVC RedirectResult class in custom authentication filter

我有簡單的自定義身份驗證過濾器:

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和帶登錄操作方法的AccountController。 Index操作方法使用我的自定義過濾器。 當我嘗試調用Index操作方法時,我的過濾器攔截了代碼執行,並重定向到Home / Account / Login url。 為什么會發生? 我希望在AccountController中調用Login操作。

您被重定向是因為您的過濾器中沒有確保用戶在重定向前未通過身份驗證的條件。

每個請求都會運行一個過濾器。 您可以將分支邏輯放入過濾器中以使其成為條件過濾器。

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/

發生這種情況是因為您給了URL即"Account/Login" 當您不使用"/"開頭URL時,它將檢查當前控制器中的action method 要重定向到正確的控制器和方法,請使用- "/APPLICATION_NAME/CONTROLLER_NAME/METHOD_NAME"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM