ASP.Net MVC 3重定向未授权的用户不能loginUrl [英] ASP.Net MVC 3 Redirect UnAuthorized User not to loginUrl

查看:160
本文介绍了ASP.Net MVC 3重定向未授权的用户不能loginUrl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用ASP.Net MVC3,并使用​​成员身份角色的项目。我用每个控制器授权。
例如:

i have a project using ASP.Net MVC3 and using membership for roles. i use authorize in every controller. eg:

[Authorize(Roles = "Administrator")]
    public ActionResult Index(string q, int i)
    {
      return View(model);
    }

如果有人不必须为管理员角色,那么它会重定向默认登录页面。如何改变它,所以它会重定向到查看/共享/ UnAuthorize.cshtml?或者,如果有人不必须为管理员角色,它会显示消息框(警告)?

if someone doesnt have role for administrator, then it will redirect to login page by default. how to change it,so it will redirect into Views/Shared/UnAuthorize.cshtml ? or maybe if someone doesnt have role for administrator, it will show message box (alert) ?

在此先感谢。

推荐答案

只需更改有在web.config中所示的页面(检查路由存在)

Just change the page that have to be shown in the web.config (check that the route exists)

<authentication mode="Forms">
  <forms loginUrl="~/UnAuthorize" timeout="2880" />
</authentication>

如果你的,相反,要重定向到每一个角色,你可以用自己的扩展AuthorizeAttribute的具体路径。事情是这样的(未测试,我写这篇文章给你一个想法)

If you, instead, want to redirect to a specific path for every roles you can extend the AuthorizeAttribute with your own. Something like this (not tested, I write this to give you an idea)

public class CheckAuthorize : ActionFilterAttribute
{
  public Roles[] Roles { get; set; }
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    //Your code to get the user
    var user = ((ControllerBase)filterContext.Controller).GetUser();

    if (user != null)
    {
      foreach (Role role in Roles)
      {
        if (role == user.Role)
          return;
      }
    }      
    RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
    if user.Role==Role.Administrator
    {
      redirectTargetDictionary.Add("action", "Unauthorized");
      redirectTargetDictionary.Add("controller", "Home");
    }
    else
    {
      redirectTargetDictionary.Add("action", "Logon");
      redirectTargetDictionary.Add("controller", "Home");
    }
    filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
  }
}

这篇关于ASP.Net MVC 3重定向未授权的用户不能loginUrl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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