Developer
Developer

Reputation: 888

Error: "This webpage has a redirect loop" in asp.net mvc

In MVC, I have created custom attribute for Session Timeout, like:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext ctx = HttpContext.Current;

        // If the browser session or authentication session has expired...
        if (ctx.Session["USER_ID"] == null )
        {
            filterContext.Result = new RedirectToRouteResult(
                   new RouteValueDictionary {
                    { "Controller", "Employer" },
                    { "Action", "SessionTimeout" }
            });

        }

        base.OnActionExecuting(filterContext);
    }
}

I mean is when session is time out, it should to redirect to "SessionTimeout" Action method, and I have placed for Controller methods like,

 [SessionExpireFilter]
  public class EmployerController : Controller
  {
   //Action Methods   
  }

But here, when Session is Timeout, it is going to action method on browser address, but it is displaying like:

 This webpage has a redirect loop

I don't know where I am going wrong?

Upvotes: 4

Views: 4605

Answers (1)

Sedat Kapanoglu
Sedat Kapanoglu

Reputation: 47680

Your SessionTimeout action causes OnActionExecuting in SessionExpireFilter to run again, which becomes an infinite loop. You can either:

  • Put SessionTimeout action in its own controller without the SessionExpireFilter attribute
  • Put SessionExpireFilter attribute to the individual actions except SessionTimeout, instead of the controller
  • Check if the current action is SessionTimeout in your OnActionExecuting code and don't perform the redirect (not the best idea because its name can change in the future and cause trouble again).

Upvotes: 4

Related Questions