基于角色的内容asp.net的MVC [英] Role-Based Content asp.net mvc

查看:260
本文介绍了基于角色的内容asp.net的MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望根据当前用户的给定角色(S)显示内容,在ASP.NET MVC。

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

比较旧的方式方法,使用的WebForms:

Compare the old fashion way, using WebForms:

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

现在我将如何去编写使用ASP.NET MVC时?
从我的角度来看,这将是错误直接将其放置在查看文件,并为每一个视图分配变量不会被pretty无论是。

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.

推荐答案

创建HTML帮助,并在其code检查当前用户角色:

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

更新:

或建立股票HTML辅助包装。举例ActionLink的(这的HtmlHelper的HtmlHelper,LINKTEXT串,串actionName,串controllerName):

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

这篇关于基于角色的内容asp.net的MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆