Tuesday, October 25, 2011

OnActionExecuting and OnAuthorization

When an attribute colors an action like so, what is it doing?

[MyActionAttribute("this","that")]

public ActionResult Index()

{

 
 

Let's take a look. We can hand in variables, mess with them, and then hand them back to the action by way of the ViewBag! Using OnActionExecuting and OnAuthorization to do the same thing here is likely overkill. You'd probably just pick one or the other. This touches on these some.

namespace MyApp.Web.UI.ActionFilters

{

   public class MyActionAttribute : ActionFilterAttribute, IAuthorizationFilter

   {

      private List<string> _stuff;

      

      public MyActionAttribute(params string[] stringBits)

      {

         this._stuff = new List<string>();

         for (int i = 0; i < stringBits.Length; i++)

         {

            _stuff.Add(stringBits[i].ToUpper());

         }

         _stuff.Add("I'm always here.");

      }

      

      public override void OnActionExecuting(ActionExecutingContext filterContext)

      {

         Authorize(filterContext);

      }

      

      public void OnAuthorization(AuthorizationContext filterContext)

      {

         Authorize(filterContext);

      }

      

      public void Authorize(ControllerContext filterContext)

      {

         if (filterContext.HttpContext.Session == null)

         {

            throw new NullReferenceException("You're session is null.");

         }

         filterContext.Controller.ViewBag.Whatever = _stuff;

      }

   }

}

No comments:

Post a Comment