如何以编程方式列出哪个ASP.Net角色可以访问页面?

Chr*_*ris 6 membership asp.net roles

有没有办法列出哪些角色可以通过代码访问给定页面?

例如,我有一个Testpage.aspx,我想在用户访问页面时列出该页面允许的角色.URLAuthorizationManager必须能够以某种方式找到它,因此必须有一种方法它知道在webconfig中为页面配置了哪些角色.或URL.

这是限制允许查看此页面的角色的webconfig.

<location path="Testpage.aspx">
    <system.web>
      <authorization>
        <allow roles ="admin,sales" />
      </authorization>
    </system.web>
  </location>
Run Code Online (Sandbox Code Playgroud)

如果我能找到解决方案,它将返回"admin","sales".谁知道我怎么能这样做?谢谢

Ron*_*erg 10

您可以在要获取信息的页面中使用以下代码.

var section = (AuthorizationSection)
    WebConfigurationManager.GetSection("system.web/authorization");
var rules = section.Rules;
var allowedRoles = rules
    .OfType<AuthorizationRule>()
    .Where(r => r.Action == AuthorizationRuleAction.Allow)
    .Select(r => r.Roles).First();
Run Code Online (Sandbox Code Playgroud)

调用的原因First()是.NET配置是分层的.假设您具有以下网站层次结构和配置:

/Default.aspx
/Web.config        (<allow roles="admin,user" />)
/SubDir/
       /Test.aspx
       /Web.config (<allow roles="admin,other" />)
Run Code Online (Sandbox Code Playgroud)

和你拨打上面的代码Test.aspx.cs,则该属性AuthorizationSection.Rules包含3分别对应于从配置项/SubDir/Web.config,Web.configmachine.config.所以第一个元素包含角色adminother.


del*_*ave -1

使用 Roles.GetAllRoles() 方法

http://msdn.microsoft.com/en-us/library/system.web.security.roles.getallroles.aspx

这是一个示例,其中列出了所有角色: http://weblogs.asp.net/scottgu/archive/2005/10/18/427754.aspx

  • 这似乎列出了应用程序中所有可用的角色——而不是可以访问该页面的角色 (3认同)