这里有一个工作示例:
[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。
这似乎是矫枉过正。你认为我最好创建一个安装需求来创建我在MVC中使用的特定角色名称? – M4V3R1CK
@ M4V3R1CK,自定义授权属性不重。请检查http://msdn.microsoft.com/en-us/library/ee707357(v=vs.91).aspx –
有没有人遇到MVC无法识别Windows角色的事件?我认为角色被转换为Windows中的组,但由于某种原因,当我将用户添加到组中时,如果该用户.IsInRole(“GroupJustAddedTo”)总是返回false,请检查MVC(使用Windows身份验证)。我不知道为什么......在服务器2003 R2的环境中启用了Windows身份验证。困惑:〜(??? – M4V3R1CK