Michael S
Michael S

Reputation: 4740

Route Constraint redirect

I would like to be able to redirect if a route constraint fails, rather than just return a 404. Here is the scenario:

Is this possible?

Upvotes: 3

Views: 1141

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039210

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:

  1. You want to add custom authorization logic to the existing attribute. In this case you derive from AuthorizeAttribute and override the AuthorizeCore and the HandleUnauthorizedRequest methods to perform the custom authorization and redirect (instead of navigating to the logon page) if this logic fails.

  2. You don't want any of the base functionality. In this case you derive from FilterAttribute and implement the IAuthorizationFilter interface and put your auhorization and redirection logic inside the OnAuthorization method.

Here's an example of how to redirect if the authorization logic fails using the filterContext that you have access everywhere:

var values = new RouteValueDictionary(new
{
    controller = "home",
    action = "index"
});
filterContext.Result = new RedirectToRouteResult(values);

Upvotes: 3

Related Questions