I’m working on a system that needs to know a user’s choice before they enter a site. Up till now the choice has been stored in a cookie and checked by JavaScript on the page load – if the cookie doesn’t exist then a dialog is shown and the user makes the choice.
Although we’d normally expect the user to arrive at the homepage of the application, they can legally follow a URL to any page within the application, so the JavaScript to check the choice exists on every page.
This has caused problems (almost always fixed by clearing cookies) so we’re switching to store the choice in the database. What we need is a neat way of making sure that all pages (MVC and Web Forms) check that the choice has been made and, if it hasn’t, either display a dialog or redirect to a page where the choice can be made.
The main thing bothering me is that to cause a redirect using MVC, I need to return a RedirectResult, and this can only be done from an Action. I don’t want every action to have code regarding this check – it seems like the kind of thing that should be possible from a base controller (in the same way a base page could cause a Response.Redirect.
Can anyone suggest a good way for all pages to perform a check on the database and then either cause a redirect or show a dialog?
Oh not at all. You could also redirect from a custom action filters.
For example you could write a custom
IAuthorizationFilterthat will check whether the user made the necessary choice and if not redirect to some given page. The check could be done against a cookie, database or wherever you decide to persist this information:Now you have different possibilities:
[EnsureChoiceHasBeenMade]attribute