ASP.NET MVC 3 OnActionExecuting causes infinite lo

2019-07-19 01:01发布

I have that overriden OnActionExecuting method (to check before action execute if user is logged in)

public class AuthenticationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        { 
            string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery);

            filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
        }
        else 
            base.OnActionExecuting(filterContext);
    }
}

Why - if user is not logged in - the response is redirected to that method again. Why ?

1条回答
劫难
2楼-- · 2019-07-19 01:43

That's probably because the controller action that you are redirecting to (the login url I think) is also decorated with this attribute. So if the user is not authenticated he gets redirected to the login action and because he is not authenticated he gets redirected to the login action and so on. Personally I would recommend you using the [Authorize] attribute instead of writing such action filter.

查看更多
登录 后发表回答