Role-Based Content asp.net mvc

后端 未结 4 409
-上瘾入骨i
-上瘾入骨i 2020-12-29 00:21

I wish to display content depending on the given role(s) of the active user , in the ASP.NET MVC.

Compare the old fashion way, using WebForms:

protec         


        
相关标签:
4条回答
  • 2020-12-29 00:37

    Create Html helper and check current user roles in its code:

    public static class Html
    {
        public static string Admin(this HtmlHelper html)
        {
            var user = html.ViewContext.HttpContext.User;
    
            if (!user.IsInRole("Administrator")) {
                // display nothing
                return String.Empty;
    
                // or maybe another link ?
            }
    
            var a = new TagBuilder("a");
            a["href"] = "#";
            a.SetInnerText("Admin");
    
            var div = new TagBuilder("div") {
                InnerHtml = a.ToString(TagRenderMode.Normal);
            }
    
            return div.ToString(TagRenderMode.Normal);
        }
    }
    

    UPDATED:

    Or create wrapper for stock Html helper. Example for ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName):

    public static class Html
    {
        public static string RoleActionLink(this HtmlHelper html, string role, string linkText, string actionName, string controllerName)
        {
            return html.ViewContext.HttpContext.User.IsInRole(role)
                ? html.ActionLink(linkText, actionName, controllerName)
                : String.Empty;
        }
    }
    
    0 讨论(0)
  • 2020-12-29 00:49

    The separation of concerns approach suggested in ASP.NET MVC 4 How do you serve different HTML based on Role? in my opinion is a better way to go.

    Personally I avoid IsInRole check as much as possible in the code and leave it to declarative means to achieve role based restriction as much as possible. This ensures code remains maintainable over time. I am not sure if this is a right or the wrong approach, but has worked well for me.

    0 讨论(0)
  • 2020-12-29 00:54

    this worked for me:

     <% MembershipUser mu = Membership.GetUser();
                        if (mu != null)
                            if (Roles.IsUserInRole(mu.UserName, "Administrator"))
                            {
                         %>
                    <li class="paddingleftThree"><%= Html.ActionLink("User Administration", "GetUsers", "Account")%></li> <%} %>
    
    0 讨论(0)
  • 2020-12-29 00:56

    No you would be placing it in the view file, like so actually:

    <% If (User.IsInRole("Administrator")) { %>
    <div>Admin text</div>
    <% } %>
    
    0 讨论(0)
提交回复
热议问题