2011-09-22 158 views
3

有谁知道是否有一种方法来使用MVC3中的控制器的Authorize属性的Web.Config AppSettings部分中的值?授权属性MVC 3&Web.Config AppSettings值

我目前使用这样的web.config中:

<add key="AdminRole" value="Admins"/> 

,然后我试图拉入类和使用的授权属性的值,但.NET抱怨的值不是常量等

我只是想能够使用web.config中设置的值来过滤授权,以便不同的部署可以使用基于他们的系统配置角色名称的变化。

任何帮助将不胜感激,谢谢!

回答

5

您将不得不编写自己的AuthorizationAttribute类,它在运行时从web.config中读取值。在.NET中,不可能使用运行时相关的值声明属性。

+0

这似乎是矫枉过正。你认为我最好创建一个安装需求来创建我在MVC中使用的特定角色名称? – M4V3R1CK

+0

@ M4V3R1CK,自定义授权属性不重。请检查http://msdn.microsoft.com/en-us/library/ee707357(v=vs.91).aspx –

+1

有没有人遇到MVC无法识别Windows角色的事件?我认为角色被转换为Windows中的组,但由于某种原因,当我将用户添加到组中时,如果该用户.IsInRole(“GroupJustAddedTo”)总是返回false,请检查MVC(使用Windows身份验证)。我不知道为什么......在服务器2003 R2的环境中启用了Windows身份验证。困惑:〜(??? – M4V3R1CK

4

这里有一个工作示例:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
public class AuthorizeByConfig : AuthorizeAttribute 
{ 

    /// <summary> 
    /// Web.config appSetting key to get comma-delimited roles from 
    /// </summary> 
    public string RolesAppSettingKey { get; set; } 

    /// <summary> 
    /// Web.config appSetting key to get comma-delimited users from 
    /// </summary> 
    public string UsersAppSettingKey { get; set; } 


    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 

     if (!String.IsNullOrEmpty(RolesAppSettingKey)) 
     { 
      string roles = ConfigurationManager.AppSettings[RolesAppSettingKey]; 
      if (!String.IsNullOrEmpty(roles)) 
      { 
       this.Roles = roles; 
      }     
     } 

     if (!String.IsNullOrEmpty(UsersAppSettingKey)) 
     { 
      string users = ConfigurationManager.AppSettings[UsersAppSettingKey]; 
      if (!String.IsNullOrEmpty(users)) 
      { 
       this.Users = users; 
      }     
     } 

     return base.AuthorizeCore(httpContext); 
    } 


} 

和装饰你的控制器类或方法,像这样:

[AuthorizeByConfig(RolesAppSettingKey = "Authorize.Roles", UsersAppSettingKey = "Authorize.Users")] 

凡Authorize.Roles和Authorize.Users的web.config中的appSettings。