Esempio n. 1
0
 private static ActionDescriptor CreateActionDescriptor()
 {
     ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(typeof(SampleController));
     var method = typeof(SampleController).GetMethod("Execute");
     ActionDescriptor actionDescriptor = new ReflectedActionDescriptor(method, "Execute", controllerDescriptor);
     return actionDescriptor;
 }
Esempio n. 2
0
		public ControllerMapper(ITypeFinder typeFinder, IDefinitionManager definitionManager)
		{
			IList<ControlsAttribute> controllerDefinitions = FindControllers(typeFinder);
			foreach (ItemDefinition id in definitionManager.GetDefinitions())
			{
				IAdapterDescriptor controllerDefinition = GetControllerFor(id, controllerDefinitions);
				if(controllerDefinition != null)
				{
					ControllerMap[id.ItemType] = controllerDefinition.ControllerName;

					// interacting with static context is tricky, here I made the assumtion that the last
					// finder is the most relevat and takes the place of previous ones, this makes a few 
					// tests pass and doesn't seem to be called in production
					foreach (var finder in PathDictionary.GetFinders(id.ItemType).Where(f => f is ActionResolver))
						PathDictionary.RemoveFinder(id.ItemType, finder);

					// Use MVC's ReflectedControllerDescriptor to find all actions on the Controller
					var methods = new ReflectedControllerDescriptor(controllerDefinition.AdapterType)
						.GetCanonicalActions()
						.Select(m => m.ActionName).ToArray();
					var actionResolver = new ActionResolver(this, methods);

					_controllerActionMap[controllerDefinition.ControllerName] = methods;

					PathDictionary.PrependFinder(id.ItemType, actionResolver);
				}
			}
		}
Esempio n. 3
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);
 }
Esempio n. 4
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 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;
 }
 /// <summary>
 /// 使用Descriptor,取程序集中所有Action的元数据
 /// </summary>
 /// <returns></returns>
 public static IEnumerable<ApplicationPermission> GetAllActionByAssembly()
 {
     var result = new List<ApplicationPermission>();
     //取程序集中的全部类型
     var types = Assembly.Load("AspNetIdentity2Permission.Mvc").GetTypes();
     //取控制器
     foreach (var type in types)
     {
         if (type.BaseType == typeof(BaseController))//如果是BaseController
         {
             //反射控制器
             var controller = new ReflectedControllerDescriptor(type);
             //取控制器的Action,共有实例方法
             var actions = controller.GetCanonicalActions();
             //构建权限
             foreach (var action in actions)
             {
                 //创建权限
                 var ap = new ApplicationPermission()
                 {
                     Action = action.ActionName,
                     Controller = controller.ControllerName,
                     //Params = FormatParams(action),
                     Description = GetDescription(action)
                 };
                 result.Add(ap);
             }
         }
     }
     return result;
 }
        public void When_getting_controller_attributes_then_builds_up_instance()
        {
            using (var container = new UnityContainer())
            {
                // Arrange
                var someInstance = new SomeClass();
                container.RegisterInstance<ISomeInterface>(someInstance);
                container.RegisterType<TestFilterAttribute>(new InjectionProperty("Some"));

                var context = new ControllerContext { Controller = new ControllerWithTypeAttribute() };
                var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType());
                var action = context.Controller.GetType().GetMethod("MyActionMethod");
                var actionDescriptor = new ReflectedActionDescriptor(action, "MyActionMethod", controllerDescriptor);
                var provider = new UnityFilterAttributeFilterProvider(container);

                // Act
                Filter filter = provider.GetFilters(context, actionDescriptor).Single();

                // Assert
                TestFilterAttribute attrib = filter.Instance as TestFilterAttribute;
                Assert.IsNotNull(attrib);
                Assert.AreEqual(FilterScope.Controller, filter.Scope);
                Assert.AreEqual(1234, filter.Order);
                Assert.AreSame(someInstance, attrib.Some);
            }
        }
Esempio n. 8
0
        public ActionResult Index()
        {
            var listOrActions = new ReflectedControllerDescriptor(this.GetType())
                .GetCanonicalActions()
                .Select(x => x.ActionName)
                .ToList();

            return View(listOrActions);
        }
        /// <summary>
        /// Resolves the action method parameters.
        /// </summary>
        /// <param name="controllerTypeResolver">The controller type resolver.</param>
        /// <param name="areaName">Name of the area.</param>
        /// <param name="controllerName">Name of the controller.</param>
        /// <param name="actionMethodName">Name of the action method.</param>
        /// <returns>
        /// A action method parameters represented as a <see cref="string"/> instance
        /// </returns>
        public IEnumerable<string> ResolveActionMethodParameters(IControllerTypeResolver controllerTypeResolver,
                                                                 string areaName, string controllerName,
                                                                 string actionMethodName)
        {
            // Is the request cached?
            string cacheKey = areaName + "_" + controllerName + "_" + actionMethodName;
            if (Cache.ContainsKey(cacheKey))
            {
                return Cache[cacheKey];
            }

            // Get controller type
            Type controllerType = controllerTypeResolver.ResolveControllerType(areaName, controllerName);

            // Get action method information
            var actionParameters = new List<string>();
            if (controllerType != null)
            {
                ControllerDescriptor controllerDescriptor = null;
                if (typeof(IController).IsAssignableFrom(controllerType))
                {
                    controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
                }
                else if (typeof(IAsyncController).IsAssignableFrom(controllerType))
                {
                    controllerDescriptor = new ReflectedAsyncControllerDescriptor(controllerType);
                }

                ActionDescriptor[] actionDescriptors = controllerDescriptor.GetCanonicalActions()
                    .Where(a => a.ActionName == actionMethodName).ToArray();

                if (actionDescriptors != null && actionDescriptors.Length > 0)
                {
                    foreach (ActionDescriptor actionDescriptor in actionDescriptors)
                    {
                        actionParameters.AddRange(actionDescriptor.GetParameters().Select(p => p.ParameterName));
                    }
                }
            }

            // Cache the result
            if (!Cache.ContainsKey(cacheKey))
            {
                try
                {
                    Cache.Add(cacheKey, actionParameters);
                }
                catch (ArgumentException)
                {
                    // Nomnomnom... We're intentionally eating it here
                }
            }

            // Return
            return actionParameters;
        }
 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();
 }
Esempio n. 11
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);
 }
Esempio n. 12
0
        public MvcActionFunction(Type controllerType, string actionName, string @namespace, string name, string description,
            FunctionCollection functionCollection)
            : base(@namespace, name, description, functionCollection)
        {
            _controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
            _actionName = actionName;

            var actions = _controllerDescriptor.GetCanonicalActions().Where(a => a.ActionName == actionName);
            Verify.That(actions.Any(), "Action name '{0}' isn't recognized", actionName);

            _routeToRender = "~/{0}/{1}".FormatWith(_controllerDescriptor.ControllerName, actionName);
        }
        static MethodInfo GetActionMethod(HttpContextBase context, RouteData routeData, ControllerBase controller)
        {
            var actionName = routeData.Values["action"] as string;
            if (actionName == null)
                return null;

            var controllerContext = new ControllerContext(context, routeData, controller);
            var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName) as ReflectedActionDescriptor;

            return actionDescriptor?.MethodInfo;
        }
 public ControllerDescriptor Create(Type controllerType)
 {
     ControllerDescriptor controllerDescriptor = null;
     if (typeof(IController).IsAssignableFrom(controllerType))
     {
         controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
     }
     else if (typeof(IAsyncController).IsAssignableFrom(controllerType))
     {
         controllerDescriptor = new ReflectedAsyncControllerDescriptor(controllerType);
     }
     return controllerDescriptor;
 }
Esempio n. 15
0
        internal static bool HasActionPermission(this HtmlHelper htmlHelper, string actionName, string controllerName)
        {
            var 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 ActionResult Redirect()
        {
            var catalog = this.Container.Catalog;
            double lowestOrder = double.MaxValue;
            Uri redirectUri = null;
            foreach (var exportInfo in catalog.FindExports<IControllerMetadata>(ContractNames.AdminController))
            {
                ReflectedControllerDescriptor descriptor = new ReflectedControllerDescriptor(exportInfo.Value);

                var controllerAttr =
                    descriptor.GetCustomAttributes(typeof(AdminControllerAttribute), true).FirstOrDefault()
                    as AdminControllerAttribute;

                if (controllerAttr == null)
                    continue;

                if (controllerAttr.Order >= lowestOrder)
                    continue;

                lowestOrder = controllerAttr.Order;

                Uri defaultTargetUrl = null;

                foreach (var actionDescriptor in descriptor.GetCanonicalActions())
                {
                    var actionAttr =
                        actionDescriptor.GetCustomAttributes(typeof(AdminActionAttribute), true).FirstOrDefault() as
                        AdminActionAttribute;
                    if (actionAttr == null)
                        continue;

                    string targetUrl = Url.Action(actionAttr.Name,
                                                  controllerAttr.Name,
                                                  new
                                                      {
                                                          packageId = exportInfo.Metadata.PackageId,
                                                          packageVersion = exportInfo.Metadata.PackageVersion
                                                      });

                    Uri target = new Uri(targetUrl, UriKind.RelativeOrAbsolute);

                    if (defaultTargetUrl == null || actionAttr.IsDefault)
                        defaultTargetUrl = target;
                }

                if (defaultTargetUrl != null)
                    redirectUri = defaultTargetUrl;
            }

            return Redirect(redirectUri.ToString());
        }
Esempio n. 17
0
        //This method checks if we have an AJAX request or not
        private bool IsAjaxRequest()
        {
            //The easy way
            bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
            || ((Request.Headers != null)
            && (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));

            //If we are not sure that we have an AJAX request or that we have to return JSON
            //we fall back to Reflection
            if (!isAjaxRequest)
            {
                try
                {
                    //The controller and action
                    string controllerName = Request.RequestContext.
                                            RouteData.Values["controller"].ToString();
                    string actionName = Request.RequestContext.
                                        RouteData.Values["action"].ToString();

                    //We create a controller instance
                    DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
                    Controller controller = controllerFactory.CreateController(
                    Request.RequestContext, controllerName) as Controller;

                    //We get the controller actions
                    ReflectedControllerDescriptor controllerDescriptor =
                    new ReflectedControllerDescriptor(controller.GetType());
                    ActionDescriptor[] controllerActions =
                    controllerDescriptor.GetCanonicalActions();

                    //We search for our action
                    foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
                    {
                        if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
                        {
                            //If the action returns JsonResult then we have an AJAX request
                            if (actionDescriptor.MethodInfo.ReturnType
                                .Equals(typeof(JsonResult)))
                                return true;
                        }
                    }
                }
                catch(Exception eeee)
                {
                    log.Exception(eeee);
                }
            }

            return isAjaxRequest;
        }
        public MvcControllerFunction(ReflectedControllerDescriptor controllerDescriptor,
            string @namespace, string name, string description, FunctionCollection functionCollection)
            : base(@namespace, name, description, functionCollection)
        {
            Verify.ArgumentNotNull(controllerDescriptor, "controllerDescriptor");

            _controllerDescriptor = controllerDescriptor;

            RequireAsyncHandler = _controllerDescriptor.ControllerType
                            .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                            .Any(method => method.ReturnType == typeof(Task)
                                           || (method.ReturnType.IsGenericType
                                               && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)));
        }
        public void UpdateActionList()
        {
            DB.ControllerActions.ToList();

            List<Type> typeList = Assembly.GetExecutingAssembly().GetExportedTypes().Where(r => r.HasBaseType(typeof(Controller))).ToList();

            //Delete non-existing controllers
            foreach (var item in typeList)
            {
                ReflectedControllerDescriptor controllerDes = new ReflectedControllerDescriptor(item);
                string controllerName = controllerDes.ControllerName;

                ControllerAction controllerOfActionAuthorization = DB.ControllerActions.Where(r => r.Controller == controllerName
                    && string.IsNullOrEmpty(r.Action)
                    && string.IsNullOrEmpty(r.HttpVerb)
                    ).FirstOrDefault();

                if (controllerOfActionAuthorization == null)
                {
                    controllerOfActionAuthorization = new ControllerAction();
                    controllerOfActionAuthorization.Controller = controllerName;
                    DB.AddToControllerActions(controllerOfActionAuthorization);
                    Save();
                }

                List<ActionDescriptor> actionDescriptorList = controllerDes.GetCanonicalActions().ToList();

                foreach (var actionDesc in actionDescriptorList)
                {
                    string parameters = string.Join(", ", actionDesc.GetParameters().Select(r => r.ParameterName));

                    string httpVerb = actionDesc.GetHttpVerb();

                    string actionName = actionDesc.ActionName;

                    ControllerAction actionOfActionAuthorization = DB.ControllerActions.Where(r => r.Controller == controllerName && r.Action == actionName && r.HttpVerb == httpVerb).FirstOrDefault();
                    if (actionOfActionAuthorization == null)
                    {
                        actionOfActionAuthorization = new ControllerAction();
                        actionOfActionAuthorization.Controller = controllerName;
                        actionOfActionAuthorization.Action = actionName;
                        actionOfActionAuthorization.Parameters = parameters;
                        actionOfActionAuthorization.HttpVerb = httpVerb;

                        DB.AddToControllerActions(actionOfActionAuthorization);
                        Save();
                    }
                }
            }
        }
        public void Before_each_test()
        {
            attribute = new SessionBasedAuthorizeAttibute();

            var controller = new FakeController();
            MvcTest.SetupControllerContext(controller);

            authorizationContext = new AuthorizationContext();
            authorizationContext.Controller = controller;
            authorizationContext.HttpContext = controller.HttpContext;

            var controllerDescriptor = new ReflectedControllerDescriptor(typeof(FakeController));
            var method = typeof(FakeController).GetMethod("Nothing");
            authorizationContext.ActionDescriptor = new ReflectedActionDescriptor(method, "Nothing", controllerDescriptor);
        }
Esempio n. 21
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();
        }
Esempio n. 22
0
        /// <summary>
        /// Avoids risking things like AmbiguousMatchException, by accessing the controller and action descriptors.
        /// </summary>
        internal IEnumerable<AuthorizeAttribute> GetAuthorizeAttributes(ControllerBase controller, string actionName)
        {
            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controller.ControllerContext, actionName);

            if (actionDescriptor == null)
            {
                // if we can't find a matching action descriptor, we just issue a warning log and trim the action from the site map.
                log.Warn(Exceptions.MiniAclModule_ActionDescriptorNotFound.FormatWith(controllerDescriptor.ControllerName, actionName));
                return new AuthorizeAttribute[] { new UnauthorizedAttribute() };
            }
            IEnumerable<AuthorizeAttribute> controllerAttributes = controllerDescriptor.GetAttributes<AuthorizeAttribute>();
            IEnumerable<AuthorizeAttribute> actionAttributes = actionDescriptor.GetAttributes<AuthorizeAttribute>();

            return controllerAttributes.Concat(actionAttributes);
        }
Esempio n. 23
0
        /// <summary>
        /// Returns true if a specific controller action exists and
        /// the user has the ability to access it.
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="actionName"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        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);
        }
Esempio n. 24
0
 private void ListValidActions(RequestContext requestContext)
 {
     ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(typeof(HomeController));
     ActionDescriptor[] actionDescriptors = controllerDescriptor.GetCanonicalActions();
     if (actionDescriptors.Any())
     {
         foreach (ActionDescriptor actionDescriptor in actionDescriptors)
         {
             requestContext.HttpContext.Response.Write(actionDescriptor.ActionName + "<br/>");
         }
     }
     else
     {
         requestContext.HttpContext.Response.Write("无合法的Action方法");
     }
 }
Esempio n. 25
0
        private Boolean IsJsonResponse(ControllerContext filterContext) {
            if (filterContext is ActionExecutedContext) {
                if (((ActionExecutedContext)filterContext).Result is JsonResult || filterContext.HttpContext.Response.ContentType.ToLower() == Curl.JsonType.ToLower()) {
                    return true;
                }
            } else if (filterContext is ExceptionContext) {
                if (filterContext.HttpContext.Response.ContentType.ToLower() == Curl.JsonType.ToLower()) return true;

                var actionName = (String)filterContext.RouteData.Values["action"];
                Type controllerType = filterContext.Controller.GetType();
                ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
                var action = (ReflectedActionDescriptor)controllerDescriptor.FindAction(filterContext.Controller.ControllerContext, actionName);
                return action.MethodInfo.ReturnType == typeof(JsonResult);
            }
            return false;
        }
        public override void OnException(ExceptionContext filterContext)
        {
            ExceptionHandlerAreaAttribute RegisteredExceptionArea = null;

            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(filterContext.Controller.GetType());
            ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(filterContext.Controller.ControllerContext, filterContext.RouteData.Values["action"].ToString());

            if (controllerDescriptor.IsDefined(typeof(ExceptionHandlerAreaAttribute), true))
                RegisteredExceptionArea = controllerDescriptor.GetCustomAttributes(typeof(ExceptionHandlerAreaAttribute), true).First() as ExceptionHandlerAreaAttribute;
            else if (actionDescriptor != null && actionDescriptor.IsDefined(typeof(ExceptionHandlerAreaAttribute), true))
                RegisteredExceptionArea = actionDescriptor.GetCustomAttributes(typeof(ExceptionHandlerAreaAttribute), true).First() as ExceptionHandlerAreaAttribute;

            if (RegisteredExceptionArea != null)
                Debug.WriteLine(RegisteredExceptionArea.RegisteredAreaName);

            base.OnException(filterContext);
        }
        //FROM: http://stackoverflow.com/questions/2721869/security-aware-action-link
        public static bool CheckHasActionPermission(ViewContext viewContext, string actionName, string controllerName = null, bool useNamespaceFallback = false)
        {
            //if the controller name is empty the ASP.NET convention is:
            //"we are linking to a different controller
            ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName)
                                                    ? viewContext.Controller
                                                    : GetControllerByName(viewContext, controllerName, useNamespaceFallback);

            var controllerContext = new ControllerContext(viewContext.RequestContext, controllerToLinkTo);

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

            var actionDescriptor = controllerDescriptor.GetCanonicalActions().Where(x => String.Equals(x.ActionName, actionName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            //Originally it was: //var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);
            //I changed it because, I want to check accessibility to an POST action. Maybe it could fail for actions for different http method and the same name

            return ActionIsAuthorized(controllerContext, actionDescriptor);
        }
Esempio n. 28
0
        protected ActionResult InvokeAction(string actionName)
        {
            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(this.GetType());
            ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(ControllerContext, actionName);
            Dictionary<string, object> parameters = 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 = ModelState,
                    ValueProvider = this.ValueProvider
                };
                parameters.Add(parameterDescriptor.ParameterName,this.ModelBinder.BindModel(ControllerContext, bindingContext));
            }
            return (ActionResult)actionDescriptor.Execute(ControllerContext,parameters);
        }
Esempio n. 29
0
 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);
 }
        /// <summary>
        /// Determines whether node is accessible to user.
        /// </summary>
        /// <param name="controllerTypeResolver">The controller type resolver.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="context">The context.</param>
        /// <param name="node">The node.</param>
        /// <returns>
        /// 	<c>true</c> if accessible to user; otherwise, <c>false</c>.
        /// </returns>
        public bool IsAccessibleToUser(IControllerTypeResolver controllerTypeResolver, DefaultSiteMapProvider provider, HttpContext context, SiteMapNode node)
        {
            // Is security trimming enabled?
            if (!provider.SecurityTrimmingEnabled)
            {
                return true;
            }

            // Is it an external node?
            var nodeUrl = node.Url;
            if (nodeUrl.StartsWith("http") || nodeUrl.StartsWith("ftp"))
            {
                return true;
            }

            // Is it a regular node?
            var mvcNode = node as MvcSiteMapNode;
            if (mvcNode == null)
            {
                throw new AclModuleNotSupportedException(
                    Resources.Messages.AclModuleDoesNotSupportRegularSiteMapNodes);
            }

            // Clickable? Always accessible.
            if (mvcNode.Clickable == false)
            {
                return true;
            }

            // Time to delve into the AuthorizeAttribute defined on the node.
            // Let's start by getting all metadata for the controller...
            var controllerType = controllerTypeResolver.ResolveControllerType(mvcNode.Area, mvcNode.Controller);
            if (controllerType == null)
            {
                return false;
            }

            // Find routes for the sitemap node's url
            HttpContextBase httpContext = new HttpContextWrapper(context);
            string originalPath = httpContext.Request.Path;
            var originalRoutes = RouteTable.Routes.GetRouteData(httpContext);
            httpContext.RewritePath(nodeUrl, true);

            HttpContextBase httpContext2 = new HttpContext2(context);
            RouteData routes = mvcNode.GetRouteData(httpContext2);
            if (routes == null)
            {
                return true; // Static URL's will have no route data, therefore return true.
            }
            foreach (var routeValue in mvcNode.RouteValues)
            {
                routes.Values[routeValue.Key] = routeValue.Value;
            }
            if (!routes.Route.Equals(originalRoutes.Route) || originalPath != nodeUrl || mvcNode.Area == String.Empty)
            {
                routes.DataTokens.Remove("area");
                //routes.DataTokens.Remove("Namespaces");
                //routes.Values.Remove("area");
            }
            var requestContext = new RequestContext(httpContext, routes);

            // Create controller context
            var controllerContext = new ControllerContext();
            controllerContext.RequestContext = requestContext;
            try
            {
                string controllerName = requestContext.RouteData.GetRequiredString("controller");
                controllerContext.Controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, controllerName) as ControllerBase;
            }
            catch
            {
                try
                {
                    controllerContext.Controller = Activator.CreateInstance(controllerType) as ControllerBase;
                }
                catch
                {
                }
            }

            ControllerDescriptor controllerDescriptor = null;
            if (typeof(IController).IsAssignableFrom(controllerType))
            {
                controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
            }
            else if (typeof(IAsyncController).IsAssignableFrom(controllerType))
            {
                controllerDescriptor = new ReflectedAsyncControllerDescriptor(controllerType);
            }

            ActionDescriptor actionDescriptor = null;
            try
            {
                actionDescriptor = controllerDescriptor.FindAction(controllerContext, mvcNode.Action);
            }
            catch
            {
            }
            if (actionDescriptor == null)
            {
                actionDescriptor = controllerDescriptor.GetCanonicalActions().Where(a => a.ActionName == mvcNode.Action).FirstOrDefault();
            }

            // Verify security
            try
            {
                if (actionDescriptor != null)
                {
            #if NET35
                    IEnumerable<AuthorizeAttribute> authorizeAttributesToCheck =
                       actionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).OfType
                           <AuthorizeAttribute>().ToList()
                           .Union(
                               controllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).OfType
                                   <AuthorizeAttribute>().ToList());
            #else
                    IEnumerable<AuthorizeAttribute> authorizeAttributesToCheck =
                        FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor)
                            .Where(f => typeof(AuthorizeAttribute).IsAssignableFrom(f.Instance.GetType()))
                            .Select(f => f.Instance as AuthorizeAttribute);
            #endif

                    // Verify all attributes
                    foreach (var authorizeAttribute in authorizeAttributesToCheck)
                    {
                        try
                        {
                            var currentAuthorizationAttributeType = authorizeAttribute.GetType();

                            var builder = new AuthorizeAttributeBuilder();
                            var subclassedAttribute =
                                currentAuthorizationAttributeType == typeof(AuthorizeAttribute) ?
                                   new InternalAuthorize(authorizeAttribute) : // No need to use Reflection.Emit when ASP.NET MVC built-in attribute is used
                                   (IAuthorizeAttribute)builder.Build(currentAuthorizationAttributeType).Invoke(null);

                            // Copy all properties
                            ObjectCopier.Copy(authorizeAttribute, subclassedAttribute);

                            if (!subclassedAttribute.IsAuthorized(controllerContext.HttpContext))
                            {
                                return false;
                            }
                        }
                        catch
                        {
                            // do not allow on exception
                            return false;
                        }
                    }
                }

                // No objection.
                return true;
            }
            finally
            {
                // Restore HttpContext
                httpContext.RewritePath(originalPath, true);
            }
        }