开发者

Can I load the 'Roles' attribute of an <asp:RoleGroup> programmatically?

开发者 https://www.devze.com 2023-02-13 00:17 出处:网络
I\'m maintaining an ASP.NET application, and right now security is defined in various places throughout the site. There is some logic in the code-behind, like if User.IsInRole(...), and there is other

I'm maintaining an ASP.NET application, and right now security is defined in various places throughout the site. There is some logic in the code-behind, like if User.IsInRole(...), and there is other logic sprinkled throughout the ASPX pages like:

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

As new feature requests come in and new roles are created, I am forced to go through the entire application and make sure I haven't missed any areas. I'd like to avoid this in the future.

How can I set the Roles attribute of the <asp:RoleGroup> element programmatically? I've tried doing something like this:

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

where GetRolesThatCanDoX() returns a comma-delimited list of role names, but my method never seems to get called.

Is it possible to do something like this in ASP.NET WebForms? Please help me decouple my code! ;-)

Solution: Phantomtypist's answer worked perfectly. My implementation of it was as follows:

ASPX:

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

Code-behind:

protected void Page_Load(object sender, EventArgs e)
{
    // Load rolegroups from UserManager
    lvDoSomeStuff.RoleGroups[0].Roles = UserManager.GetRolesThatCanDoStuff().ToArray();
    lvDoSomeOtherStuff.RoleG开发者_运维知识库roups[0].Roles = UserManager.GetRolesThatCanDoOtherStuff().ToArray();
}


Have you tried something like this...

Code:

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

}

Designer:

<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>
0

精彩评论

暂无评论...
验证码 换一张
取 消