Asp.net-Mvc

在 asp.net MVC 應用程序的 web.config 中指定角色

  • July 18, 2012

我正在使用表單身份驗證創建一個 MVC 應用程序。我正在針對活動目錄進行身份驗證,因此創建了一個自定義 RoleProvider。我的應用程序只關心一小組角色,到目前為止,我一直在我的 web.config 的 appSettings 部分定義這些角色:

<appSettings>
 <add key="DirectorRole" value="Domain\Directors" />
 <add key="ManagementRole" value="Domain\Managers" />
 ...
</appSettings>

但是,我在使用這種方法時遇到了一些問題:

  1. 我無法在我的控制器數據註釋中引用這些設置:[Authorize(Roles = ConfigurationManager.AppSettings["DirectorRole"])]因為它不會編譯,所以我必須再次指定組的名稱:[Authorize(Roles = "Domain\\Directors")]
  2. 在我的 web.config 中,我想為我的角色提供者指定 groupsToUse 並且只引用一個預先存在的列表,而不是維護同一組角色的兩個單獨的列表。

似乎必須有一種更好/可重用的方式來定義 web.config 中的角色,有人可以指出我正確的方向嗎?

我更喜歡使用自定義授權屬性。像這個。

public class MyAuthorizeAttribute : AuthorizeAttribute {

   public MyAuthorizeAttribute(params string[] roleKeys) {
       List<string> roles = new List<string>(roleKeys.Length);

       //foreach(var roleKey in roleKeys) {
           //roles.Add(ConfigurationManager.AppSettings["DirectorRole"]);
       //}
       var allRoles = (NameValueCollection)ConfigurationManager.GetSection("roles");
       foreach(var roleKey in roleKeys) {
           roles.Add(allRoles[roleKey]);
       }

       this.Roles = string.Join(",", roles);
   }
}

在您的控制器中,使用:

[MyAuthorize("DirectorRole")]

在你的 web.config

 <configSections>
   <section
     name="roles"
     type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
 </configSections>

 <roles>
   <add key="DirectorRole" value="Domain\Directors" />
   <add key="ManagementRole" value="Domain\Managers" />
 </roles>

我希望這能很好地解決您的第一個問題。一點點也可以解決第二個問題。

引用自:https://stackoverflow.com/questions/11539217