I would like to be able to redirect if a route constraint fails, rather than just return a 404. Here is the scenario:
- User hits page http://www.test.com/preview/home/
- Route constraint checks whether they can preview the page
- If not, redirect to http://www.foo.com/home/
Is this possible?
This is possible but not with route constraints. Route constraints are not intended to be used this way. If a route constraint is not satisfied the route doesn’t match. If you want to perform some authorization and redirect if this authorization fails you are better off writing a custom Authorize attribute and decorating your controller action with it.
There are 2 possibilities:
You want to add custom authorization logic to the existing attribute. In this case you derive from AuthorizeAttribute and override the
AuthorizeCoreand theHandleUnauthorizedRequestmethods to perform the custom authorization and redirect (instead of navigating to the logon page) if this logic fails.You don’t want any of the base functionality. In this case you derive from FilterAttribute and implement the
IAuthorizationFilterinterface and put your auhorization and redirection logic inside theOnAuthorizationmethod.Here’s an example of how to redirect if the authorization logic fails using the filterContext that you have access everywhere: