2011-09-07 4 views
0


사용자 지정 권한 부여 특성을 정의했으며 솔루션의 모든 작업에 자동으로 적용됩니다. OnAuthorize 메서드에서 IsDefined 메서드를 사용하여 다른 특성이 정의되어 있는지 확인하지만 항상 false를 반환하는 것으로 보입니다.MVC 3 사용자 지정 권한 부여 특성 isDefined는 항상 true를 반환합니다.

편집 : AuthorizeAttr 특성은 Global.asax의 RegisterGlobalFilters 함수에서 설정되며 Anon 특성은 권한 부여가 필요없는 작업 바로 위에 표시됩니다. 여기

내 코드입니다 : 부울 대수에서

isDefinedOnAction || isDefinedOnController 

의 부정

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 
public class Anon : Attribute { } 

public class Role : Attribute 
{ 
    public int Id; 
    public Role(int id) 
    { 
     Id = id; 
    } 
} 

public class AuthorizeAttr : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     if (!(filterContext.ActionDescriptor.IsDefined(typeof(Anon), false)) || !(filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(Anon), false))) 
     { 
      Procurement.User u = MvcApplication.GetCurrentUser(filterContext.HttpContext); 
      if (u == null || !u.enabled) 
       filterContext.Result = new RedirectResult("/Session/Login?msg=You must log in to use this site.&ReturnUrl=" + filterContext.RequestContext.HttpContext.Request.RawUrl); 
      if (filterContext.ActionDescriptor.IsDefined(typeof(Role), false)) 
      { 
       object[] criterias = filterContext.ActionDescriptor.GetCustomAttributes(typeof(Role), false); 
       bool authorized = true; 
       for (int x = 0; x < criterias.Length; x++) 
       { 
        if (((Role)criterias[x]).Id > u.roleId) 
        { 
         authorized = false; 
         break; 
        } 
       } 

       if (!authorized) 
       { 
        ContentResult C = new ContentResult(); 
        C.Content = "<h1><b>The resource is unavailable!</b></h1>"; 
        filterContext.Result = C; 
       } 
      } 
     } 

    } 
} 

답변

1

입니다 :

:
!isDefinedOnAction && !isDefinedOnController 

그래서 당신은 아마 && 조건을 원하는 당신이 ||을 원하는 경우

가 나 :

public override void OnAuthorization(AuthorizationContext filterContext) 
{ 
    var isDefinedOnAction = filterContext.ActionDescriptor.IsDefined(typeof(Anon), false); 
    var isDefinedOnController = filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(Anon), false); 
    if (isDefinedOnAction || isDefinedOnController) 
    { 
     ... the attribute is present on either a controller or an action 
     => do nothing here 
    } 
    else 
    { 
     ... perform your authorization here 
    } 
} 

을 분명히 첫 번째는 훨씬 더 읽을 것입니다.

+0

AH! Ofcource! 나는 결과를 부정하기 때문에 그것이 존재하지 않는지 검사하고 그 중 하나만 속성을 가지지 않으면 if 문에있는 코드가 실행될 수 있습니다. 간단한 논리적 인 문제를 게시하고 도움을 청합니다! –

+0

너무 빨리 말하면, 여전히 어떤 이유로 작동하지 않습니다! –

+0

@Mats Edvinsson, 코드를 테스트 한 결과 제대로 작동했습니다. if 조건 이전에'isDefinedOnAction'과'isDefinedOnController' 변수의 값은 무엇입니까? 그들은 둘 다 거짓인가? 컨트롤러 나 액션을'[Anon]'속성으로 장식 했습니까? –

관련 문제