asp.net - 我可以加载 <asp :RoleGroup> programmatically? 的 'Roles' 属性吗

标签 asp.net security webforms roles

我正在维护一个 ASP.NET 应用程序,现在安全性是在整个站点的各个位置定义的。隐藏代码中有一些逻辑,例如 if User.IsInRole(...) ,还有其他逻辑散布在 ASPX 页面中,例如:

<asp:LoginView ID="lvDoSomeStuff" runat="server">
    <RoleGroups>
        <asp:RoleGroup Roles="Accounting,HR,Blah">
        ...
    </RoleGroups>
</asp:LoginView>

随着新功能请求的出现和新角色的创建,我被迫浏览整个应用程序并确保没有遗漏任何区域。我希望将来避免这种情况。

如何设置 Roles <asp:RoleGroup> 的属性以编程方式元素?我尝试过做这样的事情:

<asp:LoginView ID="lvDoSomeStuff" runat="server">
    <RoleGroups>
        <asp:RoleGroup Roles="<%= UserManager.GetRolesThatCanDoX() %>">
        ...
    </RoleGroups>
</asp:LoginView>

哪里GetRolesThatCanDoX()返回以逗号分隔的角色名称列表,但我的方法似乎从未被调用。

是否可以在 ASP.NET WebForms 中执行类似的操作?请帮助我解耦我的代码! ;-)

解决方案: Phantomtypist's answer工作完美。我的实现如下:

ASPX:

<asp:LoginView ID="lvDoSomeStuff" runat="server">
    <RoleGroups>
        <asp:RoleGroup>
        ...
        </asp:RoleGroup>
    </RoleGroups>
</asp:LoginView>

代码隐藏:

protected void Page_Load(object sender, EventArgs e)
{
    // Load rolegroups from UserManager
    lvDoSomeStuff.RoleGroups[0].Roles = UserManager.GetRolesThatCanDoStuff().ToArray();
    lvDoSomeOtherStuff.RoleGroups[0].Roles = UserManager.GetRolesThatCanDoOtherStuff().ToArray();
}

最佳答案

你有没有尝试过这样的事情......

代码:

protected void Page_Load(Object sender, EventArgs e)
{
    RoleGroup rg = new RoleGroup();
    rg.ContentTemplate = new CustomTemplate();
    String[] RoleList = {"users"};
    rg.Roles = RoleList;
    RoleGroupCollection rgc = LoginView1.RoleGroups;
    rgc.Add(rg);

}

设计师:

<asp:LoginView id="LoginView1" runat="server">
     <AnonymousTemplate>
         You are not logged in.<br />
         <asp:LoginStatus id="LoginStatus1" runat="server"></asp:LoginStatus>
     </AnonymousTemplate>
     <LoggedInTemplate>
          You are logged in as
          <asp:LoginName id="LoginName1" runat="server" />. This message is not from the template.<br />
          <asp:LoginStatus id="Loginstatus2" runat="server"></asp:LoginStatus>
     </LoggedInTemplate>
</asp:LoginView>

关于asp.net - 我可以加载 <asp :RoleGroup> programmatically? 的 'Roles' 属性吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5106142/

相关文章:

c# - IIS 中的 "An existing connection was forcibly closed by the remote host"错误,但不是 VS 开发服务器

javascript - 是否有帮助将 Prototype JavaScript 转换为 jQuery 的资源?

asp.net - 将生成的行和列添加到 aspx 文件中的表中

c# - ValidateAntiForgeryToken token 有效但不匹配

security - 在批处理脚本中混淆密码

c# - 在 Web Forms Asp 的 URL 中调用 WebMethod

ASP.NET MVC 性能

c# - 使用 Windows 应用商店应用程序设置 SendGrid

.net - 在 Request.Form 中搜索控件/解析 NameValueCollection

security - Heroku 应用程序在 VPN 上调用外部 Web 服务