JoelFan
JoelFan

Reputation: 38714

How to avoid a redirect loop in ASP.NET MVC

In certain error conditions I would like to redirect to the Home controller but I want to make sure that I don't get into a "redirect" loop (with an exception being generated each time resulting in yet another redirect). What is the best way to do this?

Upvotes: 3

Views: 4057

Answers (3)

Tim Abell
Tim Abell

Reputation: 11881

The short answer is don't redirect to the home controller.

Instead redirect to a static error message page.

This will be cleaner and more stable.

Upvotes: 0

Matt Mitchell
Matt Mitchell

Reputation: 41823

It sounds like you're asking for a solution to the halting problem (i.e. "I want to redirect to self on exceptions but not if subsequent call will always throw an exception").

Barring implementing research in this field (while the halting problem is impossible to solve, you can eliminate quite a few cases with certain analysis) I would say your best bet is to do what firefox is doing anyway - keep a count of how many self-redirects have occurred and stop redirecting if it exceeds a certain count.

A way to do this might be to include a parameter that is incremented with each subsequent "exception throw redirect" and to compare against this parameter when deciding whether to redirect or not.

Upvotes: 3

Craig Stuntz
Craig Stuntz

Reputation: 126557

Well, the general way to stop recursion is with a stop case. In your example, whatever does the redirect could look at its referrer, and make sure it does not try to "redirect" to the referrer.

Upvotes: 1

Related Questions