The Code Slinger

December 28, 2010

Expression based RenderAction HtmlHelper extension (with Authorization)

Filed under: ASP.NET,C#,MVC — Pete @ 11:39 am

        public static void RenderAuthorizedAction<TController>(this HtmlHelper helper, Expression<Action<TController>> action) where TController : Controller

        {

            var routeValuesFromExpression = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression<TController>(action);

 

            if(helper.IsAuthorized(action))

                helper.RenderAction(routeValuesFromExpression["Action"].ToString(), routeValuesFromExpression);

        }

 

        public static bool IsAuthorized<TController>(this HtmlHelper helper, Expression<Action<TController>> action)

        {

            var call = action.Body as MethodCallExpression;

 

            if (call == null) return false;

 

            var authorizeAttributes = call.GetAttributes<IAuthorizationFilter>();

            if (authorizeAttributes.Length == 0) return true;

 

            var controllerContext = helper.ViewContext.Controller.ControllerContext;

            var controllerDescriptor = new ReflectedControllerDescriptor(typeof(TController));

            var actionDescriptor = new ReflectedActionDescriptor(call.Method, call.Method.Name, controllerDescriptor);

 

            return authorizeAttributes.All(a => IsAuthorized(a, controllerContext, actionDescriptor));

        }

I’m sure this is coming in MVC 3, however I needed it now and it’s fairly straightforward.  To use it, simply call from your View as:

<% Html.RenderAuthorizedAction<MyController>(a => a.MyActionMethod()); %>

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: