Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I ported and hacked this code from the MvcSitemap:</p> <pre><code>public static class SecurityTrimmingExtensions { /// &lt;summary&gt; /// Returns true if a specific controller action exists and /// the user has the ability to access it. /// &lt;/summary&gt; /// &lt;param name="htmlHelper"&gt;&lt;/param&gt; /// &lt;param name="actionName"&gt;&lt;/param&gt; /// &lt;param name="controllerName"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static bool HasActionPermission( this HtmlHelper htmlHelper, string actionName, string controllerName ) { //if the controller name is empty the ASP.NET convention is: //"we are linking to a different controller ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName) ? htmlHelper.ViewContext.Controller : GetControllerByName(htmlHelper, controllerName); var controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerToLinkTo); var controllerDescriptor = new ReflectedControllerDescriptor(controllerToLinkTo.GetType()); var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName); return ActionIsAuthorized(controllerContext, actionDescriptor); } private static bool ActionIsAuthorized(ControllerContext controllerContext, ActionDescriptor actionDescriptor) { if (actionDescriptor == null) return false; // action does not exist so say yes - should we authorise this?! AuthorizationContext authContext = new AuthorizationContext(controllerContext); // run each auth filter until on fails // performance could be improved by some caching foreach (IAuthorizationFilter authFilter in actionDescriptor.GetFilters().AuthorizationFilters) { authFilter.OnAuthorization(authContext); if (authContext.Result != null) return false; } return true; } private static ControllerBase GetControllerByName(HtmlHelper helper, string controllerName) { // Instantiate the controller and call Execute IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory(); IController controller = factory.CreateController(helper.ViewContext.RequestContext, controllerName); if (controller == null) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentUICulture, "Controller factory {0} controller {1} returned null", factory.GetType(), controllerName)); } return (ControllerBase)controller; } </code></pre> <p>It could use some caching but for my case that was a premature optimization.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload