【问题标题】:Check authorize(Role) inside controller in MVC4检查 MVC4 中控制器内部的授权(角色)
【发布时间】:2014-04-24 11:25:03
【问题描述】:

我在我的项目中创建了一个控制器。

         [Authorize(Roles = "Admin")]
        private StudentRepositor obj = new StudentRepositor();
        public ActionResult Index()
        {

            var model = obj.GetStudentlist();
            foreach (var stu in model)
            {
                stu.State = (stu.State == "1") ? "فعال" : "غیرفعال ";
            }
            return View(model);
        }

我想检查控制器内部而不是外部的权限。

例如这样的事情:

 public ActionResult Index()
            {

               if(Role=admin) return view2
               if(role=teacher) return view1
            }

我可以这样做吗?!!

最好的问候

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

你应该可以使用User.IsInRole()

 public ActionResult Index()
        {

           if(User.IsInRole("admin")) 
           {
               //Return View
           }
           else if(User.IsInRole("teacher")) 
           {
               //Return View
           }
           else
           {
               //Return View
           }
        }

【讨论】:

  • 如何在视图中执行此操作? IsInRole 方法无法识别。在控制器中一切正常。
【解决方案2】:

我建议你创建你的自定义 AuthorizationAttribute,像这样。

public class AuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        private readonly Type _userType;

        public AuthorizationAttribute()
        {
        }

        public AuthorizationAttribute(Type userType)
        {
            _userType = userType;
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var currentHttpContext = filterContext.RequestContext.HttpContext;
            if (!currentHttpContext.User.Identity.IsAuthenticated)
            {
                //Redirect 
            }

            if (_userType != null)
            {
                var identity = filterContext.RequestContext.HttpContext.User.Identity.Name;
                //Get type for identity

                if(_userType != identityType)
                {
                     //Redirect
                }

            }
        }
    }

之后你可以像这样使用它:

[Authorization(typeof(Admin))]
public ActionResult Create()
{}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多