2015-10-05 42 views
-1

,所以我有一個問題。我有一個控制器和一些用戶角色。我使用的字符串時,我有[Authorize(Roles="Admin")],但我想用一個枚舉一樣,因爲如果我改變角色的名字,我會在一個位置修改。 我已經嘗試過Roles=UserRoles.Admin.ToString(),其中是的UserRole我的枚舉,但我得到一個錯誤。我已經從這裏閱讀了Aricles,但似乎沒有人幫助我解決我的問題。如字符串使用枚舉點網

你能幫我解決一下嗎?

+0

創建自定義'AuthorizeAttribute'看到這樣的事情:http://stackoverflow.com/questions/13264496/asp-net-mvc-4-custom-authorize-attribute-with-permission-codes-without-roles – Ric

回答

3

像這樣創建一個自定義AuthorizeAttribute

using System.Collections.Generic; 
using System.Web.Mvc; 

namespace MyApp.Whatever 
{ 
    public class CustomAuthorizeAttribute : AuthorizeAttribute 
    { 
     public CustomAuthorizeAttribute(params UserRoles[] userRoles) 
     { 
      Roles = string.Join(",", userRoles); 
     } 
    } 
} 

然後你可以使用它,你通常會使用AuthorizeAttribute,就像這樣:

using System.Web.Mvc; 

namespace MyApp.Whatever 
{ 
    [CustomAuthorize(UserRoles.Admin, UserRoles.Whatever)] 
    public class MyController : Controller 
    { 
     ... 
    } 
} 
1

這可以完成,但你需要做一些工作。

  • 創建你自己實現IAuthorizationFilter自定義屬性(如AuthorizeAttribute一樣)
  • 接受你列舉在其構造函數(或者通過屬性)
  • 正向操作的一個包含實例AuthorizeAttribute

(整個過濾機制是可擴展的,允許這種事情。)

不過,我在過去已經完成了,處理這個問題是定義一系列傳遞給屬性實例的常量字符串。因此保持名字中心。