特定のディレクトリのアクセス権限をプログラムから調べる
フォーム認証とロールのアクセス制御を実装してみたが、
アクセス制御が設定されたページへのリンクなども、リンク先のディレクトリのアクセス制御によって、
表示/非表示を切り替えるようにしたい。
そのための、プログラムから現在のユーザがあるディレクトリへのアクセス権限があるかどうかを調べるコード。
Public Function CheckRoleFromPathForUser(ByVal mapPath As String) As Boolean '指定したディレクトリのweb.configの設定を取得 Dim configuration As System.Configuration.Configuration = _ WebConfigurationManager.OpenWebConfiguration(mapPath) 'アクセス権限のセクション取得 Dim authorizationSection As AuthorizationSection = _ CType(configuration.GetSection("system.web/authorization"), AuthorizationSection) 'ロールのString配列取得 For Each rule As AuthorizationRule In authorizationSection.Rules 'ロールの許可アクションの場合 If rule.Action = AuthorizationRuleAction.Allow And rule.Roles.Count <> 0 Then 'ロールに所属するか否か For Each role As String In rule.Roles If HttpContext.Current.User.IsInRole(role) Then Return True End If Next End If Next Return False End Function
使うときは下のように。
If Not CheckRoleFromPathForUser("~/MyPractice") Then HyperLink1.Visible = False End If