2012-01-26 3 views
0

많은 역할을 맡을 것이고 각 역할에는 많은 기능이 있으므로 내 경우에는 RequireRoles 속성으로 충분하지 않을 것입니다. 컨트롤러 동작을 동적으로 정의 할 수있는 방법이 필요합니다. 뷰의 섹션 및/또는 컨트롤보기 (뷰 내부에 if/else 로직을 추가하지 않고).MVC 3 - 역할/기능별로보기의 섹션 및/또는 컨트롤 제한

제 생각에 컨트롤러가 View에게 if/else 로직으로보기를 표시하는 것이 아니라 표시하는 방법을 말해야한다고 생각했습니다.

디자인 방법에 대한 아이디어가 있으십니까?

답변

0

먼저 속성을 사용하여 어떤 역할을 볼 롤을 제어 할 수있는 필터를 만들어야합니다. http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs을 참조하십시오.

public class RequiresRoleAttribute : ActionFilterAttribute { 
    private List<string> requiredRoles = null; 

    /// <summary> 
    /// Initializes a new instance of the <see cref="RequiresRoleAttribute"/> class. 
    /// </summary> 
    /// <param name="roleNames">The role names.</param> 
    public RequiresRoleAttribute(params string[] roleNames) { 
     this.requiredRoles = new List<string>(roleNames); 
    } 

    /// <summary> 
    /// Called by the MVC framework before the action method executes. 
    /// </summary> 
    /// <param name="filterContext">The filter context.</param> 
    public override void OnActionExecuting(ActionExecutingContext filterContext) { 
     bool hasRole = false; 

     // check to see if the user has the proper role here 

     // if the do not have the role, they are not allowed to execute the action 
     if (!hasRole) 
      throw new UserAccessException("You do not have access to this action (" + filterContext.ActionDescriptor.ActionName + ", " + filterContext.ActionDescriptor.ControllerDescriptor.ControllerName + ")"); 

     base.OnActionExecuting(filterContext); 
    } 
} 

두 번째로 논리적 인 문제를 해결하려면 역할이 필요한 각 섹션에 하위 작업을 사용할 수 있습니다. 다시 필터를 하위 작업에 적용 할 수 있습니다. 어린이 행동에 대한 자세한 내용은 http://msdn.microsoft.com/en-us/library/ie/ee839451.aspx을 참조하십시오.

변경해야 할 사항은 예외를 throw하는 섹션입니다. 실행중인 작업이 하위 작업인지 확인해야합니다. 그렇다면 빈 콘텐츠 결과를 반환하고 싶을 것입니다.