재우니의 블로그


ASP.NET MVC  에서 ACTION FILTERS 를 커스텀 하게 구현해 보고자 할때 , CONTROLLER 에서 파라미터를 사용해야 할 사항이 발생 경우에 대해 알아보죠.


아래는 CONTROLLER 에서 CUSTOM 필터를 호출할때 Role 이라는 속성에 상수 값을 던져 받아 처리하는 방법을 보여줍니다.

FILTER 에서 속성을 구현하여, 컨트롤러에서 속성에 맞게 구현하시면 됩니다. 속성이 여러 개 일 경우 , (콤마) 로 전송합니다.

** 속성이 존재할 경우 : [MustHaveRole(Role="admin", User = "shimpark")]


****** Controller 에서 filter 호출하기


[MustHaveRole(Role="admin")]

public ActionResult AdminSection()

{

    return View();

}


***** Action Filter (필터 구현)


public class MustHaveRoleAttribute : ActionFilterAttribute

{

    public string Role { get; set; }


    public override void OnActionExecuting(ActionExecutingContext filterContext)

    {

        if (!string.IsNullOrEmpty(Role))

        {

            // Use Role string to check if the current user has that role

        }

    }

}


하지만 CONTROLLER 에서 FILTER 로 속성에 상수 값 말고 상황에 따라 다르게 변수값을 할당하고 싶을때 가 있습니다.

그럴때는 FILTER 에 속성값으로 전달하지 않고, CONTROLLER 에 기재되어 있는 변수값을 ActionExecutingContext 을 통해 값을 가져올 수 있습니다.


****** Controller 에서 filter 호출하기


[MustHaveRole]

public ActionResult AdminSection()

{

    string role = "admin";

    return View();

}


** Action Filter 구현하기


public class MustHaveRoleAttribute : ActionFilterAttribute

{

    public override void OnActionExecuting(ActionExecutingContext filterContext)

    {

        string role = filterContext.ActionParameters.SingleOrDefault(p => p.Key == "role").Value.ToString();

        if (!string.IsNullOrEmpty(role)) 

        { 

            // Use role string to check if the current user has that role 

        }

    }

}


또한 CONTROLLER 에 넘어오는 파라미터 값으로도 전달 받을 수 있습니다.


****** Controller 에서 filter 호출하기


[MustHaveRole]

public ActionResult AdminSection(string role)

{

    return View();

}


** Action Filter 구현하기


public class MustHaveRoleAttribute : ActionFilterAttribute

{

    public override void OnActionExecuting(ActionExecutingContext filterContext)

    {

        string role = filterContext.ActionParameters.SingleOrDefault(p => p.Key == "role").Value.ToString();

        if (!string.IsNullOrEmpty(role)) 

        { 

            // Use role string to check if the current user has that role 

        }

    }

}



마지막으로 CONTROLLER 의 ViewBag 을 통해  FILTER 에서 가져오는 방법입니다.


****** Controller 에서 filter 호출하기


[MustHaveRole]

public ActionResult AdminSection()

{

    ViewBag.Role = "admin";

    return View();

}


** Action Filter 구현하기

public class MustHaveRoleAttribute : ActionFilterAttribute

{

    public override void OnActionExecuting(ActionExecutingContext filterContext)

    {

        string role = filterContext.Controller.ViewBag["Role"].ToString();

        if (!string.IsNullOrEmpty(role)) 

        { 

            // Use role string to check if the current user has that role 

        }

        // Further examples

        string actionName = (string)filterContext.RouteData.Values["action"];

        string controllerName = (string)filterContext.RouteData.Values["controller"];

    }

}