這裏有一個工作示例:
[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