根据用户角色角色隐藏视图中的添加/编辑操作链接

时间:2014-06-23 06:02:57

标签: asp.net-mvc-4

如何根据用户角色启用或禁用ASP.NET MVC razor视图中的添加/编辑/删除操作链接。我尝试了以下但在更新用户角色时似乎无法正常工作。

如果我更新了用户角色,则更新后的值不会刷新。它仍然可以使用旧值。如何解决此问题?

if (User.IsInRole("Admin")) 
{ 
}

3 个答案:

答案 0 :(得分:1)

在您看来,请检查以下内容:

@{
    //replace Admin with your administrator role
    if (User.IsInRole("Admin")) 
    { 
        @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
        @Html.ActionLink("Details", "Details", new { id=item.ID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.ID })
    }
}

只有这样,管理员才能看到代码块中的whasts,但这并不意味着用户无法在浏览器中手动输入url。它仍然可以访问。您也应该通过安全控制器/操作方法来保护它们:

using System.ComponentModel.DataAnnotations

[Authorize(Roles = "Admin, SuperModerator")]
public ActionResult GetMeSomething()
{
    /* ... */
}

答案 1 :(得分:1)

创建一个控制器库并覆盖OnActionExecuting方法,如下所示:

public class ControllerBase : Controller
{

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewBag.IsAdmin = User.IsInRole("Admin")

            base.OnActionExecuting(filterContext);
        }
}

在您的视图控制器中,请务必从ControllerBase派生

public class HomeController: ControllerBase
{
...
}

最后在您看来,使用viewbag的isadmin属性:

@if (ViewBag.IsAdmin==true)
{ 
  <li>@Html.ActionLink("Home Page", "Index", "Home")</li>
}

这种方法的优点是它适用于每一页。缺点是你必须使每个页面都来自ControllerBase。这并不一定是件坏事,因为它会让你在每个控制器中都拥有默认的控制器功能。

答案 2 :(得分:0)

我曾经编写过自定义Html Helper,只有当用户具有特定角色时才会呈现:

public static class LinkExtensions
{
    public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, bool showActionLinkAsDisabled = false)
    {
        return htmlHelper.ActionLinkAuthorized(linkText, actionName, null, new RouteValueDictionary(), new RouteValueDictionary(), showActionLinkAsDisabled);
    }

    public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, bool showActionLinkAsDisabled = false)
    {
        return htmlHelper.ActionLinkAuthorized(linkText, actionName, null, new RouteValueDictionary(routeValues), new RouteValueDictionary(), showActionLinkAsDisabled);
    }

    public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, bool showActionLinkAsDisabled = false)
    {
        return htmlHelper.ActionLinkAuthorized(linkText, actionName, controllerName, new RouteValueDictionary(), new RouteValueDictionary(), showActionLinkAsDisabled);
    }

    public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, RouteValueDictionary routeValues, bool showActionLinkAsDisabled = false)
    {
        return htmlHelper.ActionLinkAuthorized(linkText, actionName, null, routeValues, new RouteValueDictionary(), showActionLinkAsDisabled);
    }

    public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes, bool showActionLinkAsDisabled = false)
    {
        return htmlHelper.ActionLinkAuthorized(linkText, actionName, null, new RouteValueDictionary(routeValues), new RouteValueDictionary(htmlAttributes), showActionLinkAsDisabled);
    }

    public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes, bool showActionLinkAsDisabled = false)
    {
        return htmlHelper.ActionLinkAuthorized(linkText, actionName, null, routeValues, htmlAttributes, showActionLinkAsDisabled);
    }

    public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes, bool showActionLinkAsDisabled = false)
    {
        return htmlHelper.ActionLinkAuthorized(linkText, actionName, controllerName, new RouteValueDictionary(routeValues), new RouteValueDictionary(htmlAttributes), showActionLinkAsDisabled);
    }

    public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes, bool showActionLinkAsDisabled)
    {
        if (htmlHelper.ActionAuthorized(actionName, controllerName))
        {
            return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);
        }
        else
        {
            if (showActionLinkAsDisabled)
            {

                return MvcHtmlString.Empty;
            }
            else
            {
                return MvcHtmlString.Empty;
            }
        }
    }
}

这是ActionAuthorized()定义:

public static class ActionExtensions
{
    public static bool ActionAuthorized(this HtmlHelper htmlHelper, string actionName, string controllerName)
    {
        ControllerBase controllerBase = string.IsNullOrEmpty(controllerName) ? htmlHelper.ViewContext.Controller : htmlHelper.GetControllerByName(controllerName);
        ControllerContext controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerBase);
        ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerContext.Controller.GetType());
        ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

        if (actionDescriptor == null)
            return false;

        FilterInfo filters = new FilterInfo(FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor));

        if (!htmlHelper.CheckAccessRight(actionName, controllerDescriptor.ControllerName))
        {
            return false;
        }
        else
        {
            return true;
        }


        return true;
    }
}

在这里我从数据库中检查用户是否在角色中:

public static bool CheckAccessRight(this HtmlHelper htmlHelper,string Action, string Controller)
{
    if (HttpContext.Current.Session["userId"] != null)
    {
        string userID = HttpContext.Current.Session["userId"].ToString();
        using (var db = new cloud_clinicEntities())
        {

            assignment objAss = null;
            if (HttpContext.Current.Session["AccountType"].ToString() == "lab")
            {
                objAss = db.assignments.SingleOrDefault(model => model.userid == userID);
            }
            else
            {
                objAss = db.assignments.SingleOrDefault(model => model.employeeId == userID);
            }

            String UserRole = objAss.itemname;

            itemchildren objChild = db.itemchildrens.SingleOrDefault(model => model.parent == UserRole && model.child == Controller + " " + Action);

            if (objChild != null)
            {
                return true;
            }
            else
            {
                return false;
            }


        }
    }
    else
    {
        return false;
    }
}

并在视图中使用它:

@Html.ActionLinkAuthorized("Create New", 
                           "Create", 
                           new { org = ViewBag.OrgBranchID }, 
                           new { @id = "linkCreateEmployee" },
                           true)

现在,只有当用户处于角色中时,才会呈现此操作链接。