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()); %>