Question

I have the following route configuration in a ASP.NET MVC4 project:

routes.MapRoute(
  name:        "HttpError",
  url:         "{controller}/{id}",
  defaults:    new { controller = "Error", action = "Index" },
  constraints: new { id = @"\d+" }
);

Now, I would like to know how can I create a RedirectResult or RedirectToRouteResult that generate an URL that point to /Error/403 instead of /Error/Index/403.

Extra information

I'm trying to redirect unauthorized users from a custom implementation of System.Web.Mvc.AuthorizeAttribute inside of its overridden method: HandleUnauthorizedRequest(AuthorizationContext).

Was it helpful?

Solution

Use this in your case:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
                                                         {
                                                             {"action", "Index"},
                                                             {"controller", "Error"},
                                                             {"id", "403"},  
                                                         });
}

You have to take into account that your route has to be placed in appropriate place - before the more general routes, for example:

routes.MapRoute(
           name: "HttpError",
routes.MapRoute(
           name: "Default",

If you reverse the order, MVC will fetch the first route that fits, and redirects you for example to /Error/Index/403 instead of /Error/403.

OTHER TIPS

Redirect to Route allows you to do something similar to the following:

return RedirectToRoute("HttpError", new { controller = "Error", id = "401" }

which should generate a link without an action.

You need to change the filterContext.Result like so (for failed authorisations)

 filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new  {  Controller = "SomeController", area = "MayBeSomeArea" }));

You should do this where -where you are Overriding the HandleUnauthorizedRequest Method of the AuthorizeAttribute

I don't think this was exactly what you were looking for, but for me, just returning something like this was enough

return RedirectToRoute( new {controller = "controller_name", 
                             action = "action_name"});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top