重定向用户时授权失败的特定看法? [英] Redirect a user to a specific view when authorization fails?

查看:149
本文介绍了重定向用户时授权失败的特定看法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的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));
        }
    }

如果在当前登录用户是的不可以 Administrators角色,它踢他们回到登录屏幕。用户的登录,他们只是没有授权给执行请求的操作。

If the currently logged in user is not in the Administrators role, it kicks them back to the login screen. The user is already logged in, they are just not authorize to perform the requested action.

有什么办法让它们重新定向到一个特定的视图,例如,存取遭拒?

Is there any way to have them redirected to a specific view, for example, AccessDenied?

推荐答案

您可以定义自己的属性:

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" }
             });
         }
    }
}

和使用

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

这篇关于重定向用户时授权失败的特定看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆