Example #1
0
        public static bool ActionAuthorized(this HtmlHelper htmlHelper, string actionName, string controllerName)
        {
            ControllerBase       controllerBase       = string.IsNullOrEmpty(controllerName) ? htmlHelper.ViewContext.Controller : htmlHelper.GetControllerByName(controllerName);
            ControllerContext    controllerContext    = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerBase);
            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerContext.Controller.GetType());
            ActionDescriptor     actionDescriptor     = controllerDescriptor.FindAction(controllerContext, actionName);

            if (actionDescriptor == null)
            {
                return(false);
            }

            FilterInfo filters = new FilterInfo(FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor));

            AuthorizationContext authorizationContext = new AuthorizationContext(controllerContext, actionDescriptor);

            foreach (IAuthorizationFilter authorizationFilter in filters.AuthorizationFilters)
            {
                authorizationFilter.OnAuthorization(authorizationContext);
                if (authorizationContext.Result != null)
                {
                    return(false);
                }
            }
            return(true);
        }
        private AuthorizationContext GetAuthorizationContext <TController>() where TController : ControllerBase, new()
        {
            var controllerDescriptor = new ReflectedControllerDescriptor(typeof(TController));
            var controllerContext    = new ControllerContext(new FakeHttpContext("~/"), new RouteData(), new TController());

            return(new AuthorizationContext(controllerContext, controllerDescriptor.FindAction(controllerContext, "Index")));
        }
Example #3
0
        private static ActionDescriptor GetActionDescriptor(ControllerBase controller, RouteData routeData)
        {
            var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            var actionName           = routeData.GetRequiredString("action");
            var actionDescriptor     = controllerDescriptor.FindAction(controller.ControllerContext, actionName);

            return(actionDescriptor);
        }
Example #4
0
        public ActionResult Index()
        {
            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(typeof(HomeController));
            ActionDescriptor     actionDescriptor = controllerDescriptor.FindAction(ControllerContext, "DemoAction");
            IEnumerable <Filter> filters          = FilterProviders.Providers.GetFilters(ControllerContext, actionDescriptor);

            return(View(filters));
        }
        private static MethodInfo GetActionMethod(this ControllerContext controllerContext, IIntegratedSharedService application)
        {
            Type controllerType = controllerContext.RequestContext.GetControllerFromContext(application);
            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
            ActionDescriptor     actionDescriptor     = controllerDescriptor.FindAction(controllerContext, controllerContext.RouteData.Values.GetRouteValueDictionaryValue("action").ToString());

            return((actionDescriptor as ReflectedActionDescriptor).MethodInfo);
        }
    private ActionResult Run(string controllerName, string actionName, Dictionary <string, object> parameters)
    {
        // get the controller
        var ctrlFactory = ControllerBuilder.Current.GetControllerFactory();
        var ctrl        = ctrlFactory.CreateController(this.Request.RequestContext, controllerName) as Controller;
        var ctrlContext = new ControllerContext(this.Request.RequestContext, ctrl);
        var ctrlDesc    = new ReflectedControllerDescriptor(ctrl.GetType());
        // get the action
        var actionDesc = ctrlDesc.FindAction(ctrlContext, actionName);

        // Change the route data so the good default view will be called in time
        foreach (var parameter in parameters)
        {
            if (!ctrlContext.RouteData.Values.ContainsKey(parameter.Key))
            {
                ctrlContext.RouteData.Values.Add(parameter.Key, parameter.Value);
            }
        }
        ctrlContext.RouteData.Values["controller"] = controllerName;
        ctrlContext.RouteData.Values["action"]     = actionName;
        // To call the action in the controller, the parameter dictionary needs to have a value for each parameter, even the one with a default
        var actionParameters = actionDesc.GetParameters();

        foreach (var actionParameter in actionParameters)
        {
            if (parameters.ContainsKey(actionParameter.ParameterName))     /* If we already have a value for the parameter, change it's type */
            {
                parameters[actionParameter.ParameterName] = Convert.ChangeType(parameters[actionParameter.ParameterName], actionParameter.ParameterType);
            }
            else if (actionParameter.DefaultValue != null)     /* If we have no value for it but it has a default value, use it */
            {
                parameters[actionParameter.ParameterName] = actionParameter.DefaultValue;
            }
            else if (actionParameter.ParameterType.IsClass)                                 /* If the expected parameter is a class (like a ViewModel) */
            {
                var obj = Activator.CreateInstance(actionParameter.ParameterType);          /* Instanciate it */
                foreach (var propertyInfo in actionParameter.ParameterType.GetProperties()) /* Feed the properties */
                {
                    // Get the property alias (If you have a custom model binding, otherwise, juste use propertyInfo.Name)
                    var aliasName   = (propertyInfo.GetCustomAttributes(typeof(BindAliasAttribute), true).FirstOrDefault() as BindAliasAttribute)?.Alias ?? propertyInfo.Name;
                    var matchingKey = parameters.Keys.FirstOrDefault(k => k.Equals(aliasName, StringComparison.OrdinalIgnoreCase));
                    if (matchingKey != null)
                    {
                        propertyInfo.SetValue(obj, Convert.ChangeType(parameters[matchingKey], propertyInfo.PropertyType));
                    }
                }
                parameters[actionParameter.ParameterName] = obj;
            }
            else     /* Parameter missing to call the action! */
            {
                return(HttpNotFound());
            }
        }
        // Set culture on the thread (Because my BaseController.BeginExecuteCore won't be called)
        CultureHelper.SetImplementedCulture();
        // Return the other action result as the current action result
        return(actionDesc.Execute(ctrlContext, parameters) as ActionResult);
    }
Example #7
0
        private static MethodInfo GetActionMethod(ExceptionContext filterContext)
        {
            Type controllerType = filterContext.Controller.GetType();            // Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(x => x.Name == requestContext.RouteData.Values["controller"].ToString());
            ControllerContext    controllerContext    = new ControllerContext(filterContext.RequestContext, Activator.CreateInstance(controllerType) as ControllerBase);
            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
            ActionDescriptor     actionDescriptor     = controllerDescriptor.FindAction(controllerContext, controllerContext.RouteData.Values["action"].ToString());

            return((actionDescriptor as ReflectedActionDescriptor).MethodInfo);
        }
Example #8
0
        public void ActionDescriptorExtensions_GetFullName_call()
        {
            var controller           = new TestController();
            var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            var actionDescriptor     = controllerDescriptor.FindAction(controller.ControllerContext, "TestAction");
            var r = actionDescriptor.GetFullName();

            Assert.AreEqual("Orzoo.AspNet.Tests.TestController.TestAction", r);
        }
        public void FindActionThrowsIfActionNameIsNull()
        {
            // Arrange
            Type controllerType = typeof(MyController);
            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);

            // Act & assert
            Assert.ThrowsArgumentNullOrEmpty(
                delegate { cd.FindAction(new Mock <ControllerContext>().Object, null); }, "actionName");
        }
        public void FindActionThrowsIfControllerContextIsNull()
        {
            // Arrange
            Type controllerType = typeof(MyController);
            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);

            // Act & assert
            Assert.ThrowsArgumentNull(
                delegate { cd.FindAction(null, "someName"); }, "controllerContext");
        }
Example #11
0
        protected virtual Type FindModelType(ControllerBase controller, string actionName)
        {
            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            var actionDescriptor = controllerDescriptor.FindAction(controller.ControllerContext, actionName);
            var qry = from p in actionDescriptor.GetParameters()
                      let paramType = p.ParameterType
                                      where typeof(Csla.Core.IBusinessObject).IsAssignableFrom(paramType)
                                      select paramType;

            return(qry.SingleOrDefault());
        }
        public void FindActionReturnsNullIfNoActionFound()
        {
            // Arrange
            Type controllerType = typeof(MyController);
            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);

            // Act
            ActionDescriptor ad = cd.FindAction(new ControllerContext(), "NonExistent");

            // Assert
            Assert.Null(ad);
        }
Example #13
0
        public void FindActionThrowsIfActionNameIsEmpty()
        {
            // Arrange
            Type controllerType = typeof(MyController);
            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);

            // Act & assert
            ExceptionHelper.ExpectArgumentExceptionNullOrEmpty(
                delegate {
                cd.FindAction(new Mock <ControllerContext>().Object, "");
            }, "actionName");
        }
Example #14
0
        public ActionResult Index()
        {
            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(typeof(HomeController));
            ActionDescriptor     actionDescriptor     = controllerDescriptor.FindAction(ControllerContext, "DemoAction");
            Dictionary <ParameterDescriptor, IModelBinder> binders = new Dictionary <ParameterDescriptor, IModelBinder>();

            foreach (ParameterDescriptor parameterDescriptor in actionDescriptor.GetParameters())
            {
                binders.Add(parameterDescriptor, this.GetModelBinder(parameterDescriptor));
            }
            return(View(binders));
        }
        public static bool HasActionPermission(this AjaxHelper htmlHelper, string actionName, string controllerName)
        {
            ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName)
                ? htmlHelper.ViewContext.Controller
                : GetControllerByName(htmlHelper, controllerName);

            ControllerContext controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerToLinkTo);

            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerToLinkTo.GetType());
            ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

            return(ActionIsAuthorized(controllerContext, actionDescriptor));
        }
Example #16
0
        public ActionResult Yes(ConfirmationActionViewModel model)
        {
            if (!model.HttpPost)
            {
                return(Redirect(model.YesUrl));
            }

            ConfirmationData data = ConfirmationService.GetData(model.Id);

            RouteData route = RoutesHelper.GetRouteDataByUrl("/" + model.YesUrl);

            //var controllerDescriptor = new ReflectedControllerDescriptor(GetType());
            string controllerName = (String)route.Values["controller"];
            string actionName     = (String)route.Values["action"];
            //string values = RouteData.GetRequiredString("id");

            //IControllerActivator
            DefaultControllerFactory d = new DefaultControllerFactory();

            IController controller = d.CreateController(HttpContext.Request.RequestContext, controllerName);

            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            //d.ReleaseController(controller);

            ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(ControllerContext, actionName);

            RequestContext requestContext = new RequestContext(new RoutesHelper.RewritedHttpContextBase("/" + model.YesUrl), route);

            requestContext.HttpContext.Request.Form.Add((NameValueCollection)data.PostData);

            ControllerContext            ctx         = new ControllerContext(requestContext, (ControllerBase)controller);
            IDictionary <string, object> parameters2 = GetParameterValues(ctx, actionDescriptor);
            IDictionary <string, object> parameters  = new Dictionary <string, object>();

            ControllerContext.HttpContext.Response.Clear();
            NameValueCollection nameValueCollection = data.PostData as NameValueCollection;

            //nameValueCollection.
            actionDescriptor.Execute(ControllerContext, (IDictionary <string, object>)data.PostData);

            //var viewResult = new ViewResult
            //{
            //    ViewName = "",
            //    MasterName = "",
            //    ViewData = new ViewDataDictionary(data.PostData),
            //    TempData = null
            //};

            //return viewResult;
            return(new EmptyResult());
        }
Example #17
0
        public static ActionDescriptor GetActionDescriptor(HttpContextBase context, string controllerName, string actionName)
        {
            var controllerFactory = ControllerBuilder.Current.GetControllerFactory();

            var controller = (ControllerBase)controllerFactory.CreateController(new RequestContext(context, new RouteData()), controllerName);

            var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());

            var controllerContext = new ControllerContext(context, new RouteData(), controller);

            var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

            return(actionDescriptor);
        }
Example #18
0
        /// <summary>
        /// Determines if specified action is accessible to current user.
        /// </summary>
        /// <param name="htmlHelper">HtmlHelper object.</param>
        /// <param name="actionName">Action name to test.</param>
        /// <param name="controllerBase">Controller to test.</param>
        /// <returns>True/false if action is accessible to current user.</returns>
        private static bool ActionIsAccessibleToUser(this HtmlHelper htmlHelper, string actionName, ControllerBase controllerBase)
        {
            // Get controller context.
            var controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerBase);

            // Get controller descriptor.
            var controllerDescriptor = new ReflectedControllerDescriptor(controllerBase.GetType());

            // Get action descriptor.
            var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

            // Check on authorization.
            return(ActionIsAuthorized(actionDescriptor, controllerContext));
        }
        private DefaultContractResolver GetExecutingControllerSerializer()
        {
            var controllerDescriptor = new ReflectedControllerDescriptor(ControllerContext.Controller.GetType());
            var action           = RouteData.GetRequiredString("action");
            var actionDescriptor = controllerDescriptor.FindAction(ControllerContext, action);

            Attributes.SerializerAttribute attribute = (Attributes.SerializerAttribute)
                                                           (actionDescriptor.GetCustomAttributes(typeof(Attributes.SerializerAttribute), true).FirstOrDefault() ??
                                                           controllerDescriptor.GetCustomAttributes(typeof(Attributes.SerializerAttribute), true).FirstOrDefault());
            if (attribute != null)
            {
                return(CacheHelper.GetFromCacheOrDefault <DefaultContractResolver>(HttpContext, attribute.Serializer));
            }
            return(null);
        }
Example #20
0
        public IEnumerable <Attribute> GetAttributes(
            string actionName,
            string controllerName,
            string method = "GET")
        {
            var controllerFactory    = ControllerBuilder.Current.GetControllerFactory();
            var otherController      = (ControllerBase)controllerFactory.CreateController(new RequestContext(_htmlHelper.ViewContext.HttpContext, new RouteData()), controllerName);
            var controllerDescriptor = new ReflectedControllerDescriptor(otherController.GetType());
            var controllerContext2   = new ControllerContext(new HttpContextWrapperWithHttpMethod(_htmlHelper.ViewContext.HttpContext.ApplicationInstance.Context, method),
                                                             new RouteData(), otherController);
            var actionDescriptor = controllerDescriptor.FindAction(controllerContext2, actionName);
            var attributes       = actionDescriptor.GetCustomAttributes(true).Cast <Attribute>().ToArray();

            return(attributes);
        }
Example #21
0
        public void FindActionReturnsActionDescriptorIfFound()
        {
            // Arrange
            Type       controllerType        = typeof(MyController);
            MethodInfo targetMethod          = controllerType.GetMethod("AliasedMethod");
            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);

            // Act
            ActionDescriptor ad = cd.FindAction(new Mock <ControllerContext>().Object, "NewName");

            // Assert
            Assert.AreEqual("NewName", ad.ActionName);
            Assert.IsInstanceOfType(ad, typeof(ReflectedActionDescriptor));
            Assert.AreSame(targetMethod, ((ReflectedActionDescriptor)ad).MethodInfo, "MethodInfo pointed to wrong method.");
            Assert.AreSame(cd, ad.ControllerDescriptor, "Controller did not point back to correct descriptor.");
        }
Example #22
0
        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));
        }
        public void FindActionReturnsActionDescriptorIfFound()
        {
            // Arrange
            Type       controllerType        = typeof(MyController);
            MethodInfo targetMethod          = controllerType.GetMethod("AliasedMethod");
            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);

            // Act
            ActionDescriptor ad = cd.FindAction(new ControllerContext(), "NewName");

            // Assert
            Assert.Equal("NewName", ad.ActionName);
            Assert.IsType <ReflectedActionDescriptor>(ad);
            Assert.Same(targetMethod, ((ReflectedActionDescriptor)ad).MethodInfo);
            Assert.Same(cd, ad.ControllerDescriptor);
        }
    private ActionResult Run(string controllerName, string actionName, Dictionary <string, object> parameters)
    {
        // get the controller
        var ctrlFactory = ControllerBuilder.Current.GetControllerFactory();
        var ctrl        = ctrlFactory.CreateController(this.Request.RequestContext, controllerName) as Controller;
        var ctrlContext = new ControllerContext(this.Request.RequestContext, ctrl);
        var ctrlDesc    = new ReflectedControllerDescriptor(ctrl.GetType());
        // get the action
        var actionDesc = ctrlDesc.FindAction(ctrlContext, actionName);

        // Change the route data so the good default view will be called in time
        foreach (var parameter in parameters)
        {
            if (!ctrlContext.RouteData.Values.ContainsKey(parameter.Key))
            {
                ctrlContext.RouteData.Values.Add(parameter.Key, parameter.Value);
            }
        }
        ctrlContext.RouteData.Values["controller"] = controllerName;
        ctrlContext.RouteData.Values["action"]     = actionName;
        // To call the action in the controller, the parameter dictionary needs to have a value for each parameter, even the one with a default
        var actionParameters = actionDesc.GetParameters();

        foreach (var actionParameter in actionParameters)
        {
            if (parameters.ContainsKey(actionParameter.ParameterName))     /* If we already have a value for the parameter, change it's type */
            {
                parameters[actionParameter.ParameterName] = Convert.ChangeType(parameters[actionParameter.ParameterName], actionParameter.ParameterType);
            }
            else if (actionParameter.DefaultValue != null)     /* If we have no value for it but it has a default value, use it */
            {
                parameters[actionParameter.ParameterName] = actionParameter.DefaultValue;
            }
            else     /* Parameter missing to call the action! */
            {
                return(HttpNotFound());
            }
        }
        // Set culture on the thread (Because my BaseController.BeginExecuteCore won't be called)
        CultureHelper.SetImplementedCulture();
        // Return the other action result as the current action result
        return(actionDesc.Execute(ctrlContext, parameters) as ActionResult);
    }
Example #25
0
        public static ActionResult Run(this Controller helper, string moduleId, string controllerName, string actionName, RouteValueDictionary routeValues = null)
        {
            if (!isModuleCallValid(moduleId) || !isActionCallValid(moduleId, controllerName, actionName, false))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NotAcceptable, "Not Acceptable."));
                //throw new InvalidOperationException("Bad Request");
            }
            controllerName = controllerName + "Controller";

            Type controllerType = ModuleManager.GetModuleInfo(moduleId).Plugin.GetType().Assembly
                                  .GetTypes().Where(p => p.Name.Equals(controllerName)).First();

            if (!ControllerBuilder.Current.DefaultNamespaces.Contains(controllerType.Namespace))
            {
                ControllerBuilder.Current.DefaultNamespaces.Add(controllerType.Namespace);
            }
            try
            {
                Controller ctrl        = DependencyResolver.Current.GetService(controllerType) as Controller;
                var        ctrlContext = new ControllerContext(helper.Request.RequestContext, ctrl);
                ctrl.ControllerContext = ctrlContext;

                var ctrlDesc = new ReflectedControllerDescriptor(ctrl.GetType());
                // get the action descriptor
                var actionDesc = ctrlDesc.FindAction(ctrlContext, actionName);

                try
                {
                    // execute
                    var result = actionDesc.Execute(ctrlContext, routeValues) as ActionResult;
                    return(result);
                }
                catch (Exception ex)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, String.Format("Action failed to execute. Reason: {0}", ex.Message)));
                }
            }
            catch (Exception ex)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable, String.Format("Service Unavailable. Reason: {0}", ex.Message)));
            }
        }
        /// <summary>
        /// Runs all authorization filters just like MVC does.
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="actionName"></param>
        /// <param name="httpMethod"></param>
        /// <returns></returns>
        public static ActionResult RunOnAuthorization(Controller controller, string actionName = null, string httpMethod = null)
        {
            // reference: http://haacked.com/archive/2008/08/13/aspnetmvc-filters.aspx
            // reference: http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs
            // Filter execution order: Authorization, Action Execution, Result Execution, Exception Handling

            httpMethod = httpMethod ?? controller.ControllerContext.HttpContext.Request.HttpMethod ?? "GET";
            actionName = actionName ?? controller.ControllerContext.RouteData.GetRequiredString("action");
            if (string.IsNullOrEmpty(actionName))
            {
                throw new Exception("actionName is null or empty");
            }

            var controllerContextWithMethodParam = new ControllerContext(
                new MvcHelper.MockHttpContext {
                Request2 = new MvcHelper.MockHttpRequest {
                    HttpMethod2 = httpMethod
                }
            },
                new RouteData(),
                controller);

            var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            var actionDescriptor     = controllerDescriptor.FindAction(controllerContextWithMethodParam, actionName);

            var authorizationContext = new AuthorizationContext(controller.ControllerContext, actionDescriptor);

            var filters = GetFilters <IAuthorizationFilter>(controller, actionDescriptor, actionName, httpMethod);

            foreach (var eachFilter in filters)
            {
                eachFilter.OnAuthorization(authorizationContext);

                if (authorizationContext.Result != null)
                {
                    return(authorizationContext.Result);
                }
            }

            return(null);
        }
Example #27
0
    public static bool CheckAccess(RequestContext requestContext)
    {
        var routeData      = requestContext.RouteData;
        var controllerName = routeData.Values["controller"] as string;
        var actionName     = routeData.Values["action"] as string;

        var controller           = GetControllerByName(requestContext, controllerName);
        var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
        var controllerContext    = new ControllerContext(requestContext, controller);
        var actionDescriptor     = controllerDescriptor.FindAction(controllerContext, actionName);
        var resourceClaims       = actionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(ClaimsAuthorizeAttribute), false)
                                   .Cast <ClaimsAuthorizeAttribute>()
                                   .SelectMany(auth => auth.GetClaims()).ToList();

        resourceClaims.AddRange(actionDescriptor.GetCustomAttributes(typeof(ClaimsAuthorizeAttribute), false).Cast <ClaimsAuthorizeAttribute>()
                                .SelectMany(c => c.GetClaims()));

        var hasAccess = ClaimsAuthorization.CheckAccess(actionName, resourceClaims.ToArray());

        return(hasAccess);
    }
        /// <summary>
        /// Runs the action filter's OnActionExecuting methods.
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="actionName"></param>
        /// <param name="httpMethod"></param>
        /// <returns></returns>
        public static ActionResult RunOnActionExecuting(Controller controller, string actionName = null, string httpMethod = null)
        {
            httpMethod = httpMethod ?? controller.ControllerContext.HttpContext.Request.HttpMethod ?? "GET";
            actionName = actionName ?? controller.ControllerContext.RouteData.GetRequiredString("action");
            if (string.IsNullOrEmpty(actionName))
            {
                throw new Exception("actionName is null or empty");
            }

            var controllerContextWithMethodParam = new ControllerContext(
                new MvcHelper.MockHttpContext {
                Request2 = new MvcHelper.MockHttpRequest {
                    HttpMethod2 = httpMethod
                }
            },
                new RouteData(),
                controller);

            var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            var actionDescriptor     = controllerDescriptor.FindAction(controllerContextWithMethodParam, actionName);

            var actionExecutingContext = new ActionExecutingContext(
                controller.ControllerContext,
                actionDescriptor,
                new Dictionary <string, object>());

            var filters = GetFilters <IActionFilter>(controller, actionDescriptor, actionName, httpMethod);

            foreach (var eachFilter in filters)
            {
                eachFilter.OnActionExecuting(actionExecutingContext);

                if (actionExecutingContext.Result != null)
                {
                    return(actionExecutingContext.Result);
                }
            }

            return(null);
        }
        public static object InvokeAction(this Controller controller, string actionName)
        {
            IModelBinder                modelBinder          = new MyDefaultModelBinder();
            ControllerDescriptor        controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            ActionDescriptor            actionDescriptor     = controllerDescriptor.FindAction(controller.ControllerContext, actionName);
            Dictionary <string, object> arguments            = new Dictionary <string, object>();

            foreach (ParameterDescriptor parameterDescriptor in actionDescriptor.GetParameters())
            {
                string modelName = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;
                ModelBindingContext bindingContext = new ModelBindingContext
                {
                    FallbackToEmptyPrefix = parameterDescriptor.BindingInfo.Prefix == null,
                    ModelMetadata         = ModelMetadataProviders.Current.GetMetadataForType(null, parameterDescriptor.ParameterType),
                    ModelName             = modelName,
                    ModelState            = controller.ModelState,
                    ValueProvider         = controller.ValueProvider
                };
                object argument = modelBinder.BindModel(controller.ControllerContext, bindingContext);
                arguments.Add(parameterDescriptor.ParameterName, argument);
            }
            return(actionDescriptor.Execute(controller.ControllerContext, arguments));
        }
Example #30
0
        public static bool HasActionPermission(string actionName, string controllerName, ControllerContext currentControlerContext)
        {
            HtmlHelper htmlHelper = new HtmlHelper(new ViewContext(currentControlerContext, new WebFormView(currentControlerContext, "omg"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());

            //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);

            if (actionDescriptor == null)
            {
                actionDescriptor = controllerDescriptor.GetCanonicalActions().FirstOrDefault(a => a.ActionName == actionName);
            }

            return(ActionIsAuthorized(controllerContext, actionDescriptor));
        }