Asp.net mvc 3 web系统权限最佳实践

Asp.net mvc 3 web系统权限最佳实践,asp.net-mvc-3,web-applications,permissions,Asp.net Mvc 3,Web Applications,Permissions,我有一个asp.net MVC 3系统,不同的操作有不同的权限 使用定义所需用户权限的属性管理所有权限 我还想删除用户不允许点击的任何按钮(或链接) 在我看来,有没有什么方法可以在不做很多if-s的情况下做到这一点 谢谢 在我看来,有没有什么方法可以在不做很多if-s的情况下做到这一点 您可以编写自定义HTML帮助程序来生成这些按钮。例如: @Html.Button("button text", "role1,role2"); public static class HtmlExtension

我有一个asp.net MVC 3系统,不同的操作有不同的权限

使用定义所需用户权限的属性管理所有权限

我还想删除用户不允许点击的任何按钮(或链接)

在我看来,有没有什么方法可以在不做很多if-s的情况下做到这一点

谢谢

在我看来,有没有什么方法可以在不做很多if-s的情况下做到这一点

您可以编写自定义HTML帮助程序来生成这些按钮。例如:

@Html.Button("button text", "role1,role2");
public static class HtmlExtensions
{
    public static IHtmlString Button(this HtmlHelper htmlHelper, string buttonText, string roles)
    {
        var rolesSplit = (roles ?? string.Empty).Split(',');
        var user = htmlHelper.ViewContext.HttpContext.User;
        if (!user.Identity.IsAuthenticated || !rolesSplit.Any(user.IsInRole))
        {
            return MvcHtmlString.Empty;
        }

        var button = new TagBuilder("button");
        button.SetInnerText(buttonText);
        return new HtmlString(button.ToString());
    }
}
自定义助手将检查当前用户是否拥有所需的角色之一,并且仅在这种情况下生成相应的按钮

例如:

@Html.Button("button text", "role1,role2");
public static class HtmlExtensions
{
    public static IHtmlString Button(this HtmlHelper htmlHelper, string buttonText, string roles)
    {
        var rolesSplit = (roles ?? string.Empty).Split(',');
        var user = htmlHelper.ViewContext.HttpContext.User;
        if (!user.Identity.IsAuthenticated || !rolesSplit.Any(user.IsInRole))
        {
            return MvcHtmlString.Empty;
        }

        var button = new TagBuilder("button");
        button.SetInnerText(buttonText);
        return new HtmlString(button.ToString());
    }
}