1

谁能告诉我如何在 mvc3 中为所有操作方法实现基于角色的授权。到目前为止,在我的应用程序中,我还没有编写任何代码来跟踪用户角色。

仅在应用程序的主菜单中检查角色以构建菜单,但我想在他键入 url 时拒绝用户访问。我正在考虑实现属性。任何人都可以给我建议。

提前致谢

4

1 回答 1

0

试试下面的东西。

protected override void OnAuthorization(AuthorizationContext filter_context)
{
    #region If auth cookie is present
    if (auth_cookie != null)
    {
        #region IF loggedin user is a member
        if (SiteUsers.LoggedInUser.UserRole == UserRole.Buyer
            && filter_context.ActionDescriptor.ControllerDescriptor.ControllerName == "Home"
            && filter_context.ActionDescriptor.ActionName == "Index")
        {
            filter_context.Result = RedirectToAction("Index", "Home");
        }
        #endregion

        #region If loggedin user is a super admin
        else if (SiteUsers.LoggedInUser.UserRole == UserRole.Administrator && !filter_context.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(Adminstrator), false).Any())
        {
            if (!filter_context.ActionDescriptor.GetCustomAttributes(typeof(AllowAdmin), false).Any())
            {
                filter_context.Result = RedirectToAction("Home", "Admin");
            }

        }
        #endregion

        ViewBag.SiteUsers = SiteUsers;
    }
    #endregion

    #region if authorization cookie is not present and the action method being called is not marked with the [SkipAuthentication] attribute
    else if (!filter_context.ActionDescriptor.GetCustomAttributes(typeof(SkipAuthentication), false).Any())
    {
        if (Request.IsAjaxRequest()) filter_context.Result = Json(new ActionOutput { Results = new List<string> { Url.Action("Signin", "Home") }, Status = ActionStatus.Error }, JsonRequestBehavior.AllowGet);
        else
            filter_context.Result = RedirectToAction("Signin", "Home");
    }
    #endregion

    #region if authorization cookie is not present and the action method being called is marked with the [SkipAuthentication] attribute
    else
    {
        SiteUsers = new ReplictivityUserDetails();
        ViewBag.SiteUsers = SiteUsers;
    }
    #endregion
}
于 2013-10-14T11:16:08.807 回答