简体   繁体   中英

Role-Based Content asp.net mvc

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:

protected void Page_Load(Object sender, EventArgs e)
{
   if(User.IsInRole("Administrator")) {
       adminLink.Visible = true;
   }
}

Now how would I go on writing that when using the ASP.NET MVC ? From my point of view, it would be wrong to place it directly in the View File, and assigning a variable for every single view won't be pretty either.

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;
    }
}

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

<% If (User.IsInRole("Administrator")) { %>
<div>Admin text</div>
<% } %>

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> <%} %>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM