Redirect user to specific view when authorization fails?

I have the following code:

    [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = RoleKeys.Administrators)]
    public ActionResult Edit(int id, FormCollection collection)
    {
        User user = userRepository.GetUser(id);

        try
        {
            this.UpdateModel(user);

            userRepository.Save();

            return this.RedirectToAction("Details", new { id = user.UserId });
        }
        catch
        {
            this.ModelState.AddModelErrors(user.GetRuleViolations());

            return View(new UserFormViewModel(user));
        }
    }

If the current user is not logged in as Administrators, he returns them to the login screen. The user is already registered, they simply are not authorized to perform the requested action.

Is there a way to redirect them to a specific view like AccessDenied?

+5
source share
1 answer

You can define your own attribute:

public class MyAuthorizeAttribute: AuthorizeAttribute
{
    public override void OnAuthorization( AuthorizationContext filterContext )
    {
         base.OnAuthorization(filterContext);
         if (filterContext.Result is HttpUnauthorizedResult)
         {
             filterContext.Result = new RedirectToRouteResult(
             new RouteValueDictionary
             {
                 { "controller", "Login" },
                 { "action", "AccessDenied" }
             });
         }
    }
}

and use

[AcceptVerbs(HttpVerbs.Post), MyAuthorize(Roles = RoleKeys.Administrators)]
+5
source

All Articles