ASP.NET MVC 3 OnActionExecuting causes infinite lo

2019-07-19 00:50发布

问题:

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:

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.