2012-06-08 17 views
5

我正在使用MVC3/4。但這只是授權中的一個普遍問題。如何編寫AuthorizeAttribute(如果角色包含空格)

我所擁有的一個角色是在數據庫中名爲「Trip Leader」,它包含一個空格。我試過[Authorize(Roles="'Trip Leader', Administrator")]但它失敗了。誰能幫忙?

+0

嘗試製作,其值之旅 「領袖」 恆定? – Charmander

+0

如何? '[授權(角色= TripLeader, 「管理員」)]'?它不會工作。 – Blaise

+0

@Blaise你是否設法做到了這一點? – horgh

回答

3

創建自己的屬性,並從AuthorizeAttribute派生。然後重寫AuthorizeCore方法並通過對包含空間的角色進行驗證來實現自己的邏輯。

一個例子可能是這樣的:

public class CustomAuthAttribute : AuthorizeAttribute 
{ 
    private readonly IUserRoleService _userRoleService; 
    private string[] _allowedRoles; 

    public CustomAuthAttribute(params string[] roles) 
    { 
     _userRoleService = new UserRoleService(); 
     _allowedRoles = roles; 
    } 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
    //something like this. 
    var userName = httpContext.User.Identity.Name; 
    var userRoles = _userRoleService .GetUserRoles(userName); // return list of strings 
    return _allowedRoles.Any(x => userRoles.Contains(x)); 
    } 

}

使用

[CustomAuth("role withspace","admin")] 
public ActionResult Index() 
{ 
} 
+0

不錯!謝謝。 – Blaise

+0

歡迎您,很高興幫助! –

0

試試這個:

[Authorize(Roles="Trip Leader")] 
[Authorize(Roles="Administrator")] 

編輯:上面的代碼需要用戶來滿足這兩個角色。如果你正在尋找一個非此即彼/或授權,試試這個:

[Authorize(Roles="Trip Leader, Administrator")] 
+1

嘿,它不會工作! – Blaise

+0

似乎沒有可以將多個授權屬性放在同一個類或函數上。你可以在類和函數上看到不同的形式,而逗號形成一個或。 –

相關問題