public void ExecuteThrowsIfParametersIsMissingAValue()
        {
            // Arrange
            ReflectedActionDescriptor   ad         = GetActionDescriptor(_int32EqualsIntMethod);
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            // Act & assert
            Assert.Throws <ArgumentException>(
                delegate
            {
                ad.Execute(new Mock <ControllerContext>().Object, parameters);
            },
                "The parameters dictionary does not contain an entry for parameter 'obj' of type 'System.Int32' for method 'Boolean Equals(Int32)' in 'System.Int32'. The dictionary must contain an entry for each parameter, including parameters that have null values."
                + Environment.NewLine
                + "Parameter name: parameters"
                );
        }
        public void GetCustomAttributesWithAttributeTypeCallsMethodInfoGetCustomAttributes()
        {
            // Arrange
            object[]          expected   = new object[0];
            Mock <MethodInfo> mockMethod = new Mock <MethodInfo>();

            mockMethod
            .Setup(mi => mi.GetCustomAttributes(typeof(ObsoleteAttribute), true))
            .Returns(expected);
            ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);

            // Act
            object[] returned = ad.GetCustomAttributes(typeof(ObsoleteAttribute), true);

            // Assert
            Assert.Same(expected, returned);
        }
        public void GetFilters_IncludesTypeAttributesFromDerivedTypeWhenMethodIsOnBaseClass()
        { // DDB #208062
            // Arrange
            var context = new ControllerContext {
                Controller = new DerivedController()
            };
            var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType());
            var action           = context.Controller.GetType().GetMethod("MyActionMethod");
            var actionDescriptor = new ReflectedActionDescriptor(action, "MyActionMethod", controllerDescriptor);
            var provider         = new FilterAttributeFilterProvider();

            // Act
            IEnumerable <Filter> filters = provider.GetFilters(context, actionDescriptor);

            // Assert
            Assert.NotNull(filters.Select(f => f.Instance).Cast <MyFilterAttribute>().Single());
        }
        public void GetFilters_IncludesAttributesOnActionMethod() {
            // Arrange
            var context = new ControllerContext { Controller = new ControllerWithActionAttribute() };
            var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType());
            var action = context.Controller.GetType().GetMethod("MyActionMethod");
            var actionDescriptor = new ReflectedActionDescriptor(action, "MyActionMethod", controllerDescriptor);
            var provider = new FilterAttributeFilterProvider();

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

            // Assert
            MyFilterAttribute attrib = filter.Instance as MyFilterAttribute;
            Assert.IsNotNull(attrib);
            Assert.AreEqual(FilterScope.Action, filter.Scope);
            Assert.AreEqual(1234, filter.Order);
        }
        public override IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary <string, object> parameters, AsyncCallback callback, object state)
        {
            Task result = new ReflectedActionDescriptor(this.MethodInfo, this.ActionName, this.ControllerDescriptor).Execute(controllerContext, parameters) as Task;

            if (result == null)
            {
                throw new InvalidOperationException(string.Format("Method {0} should have returned a Task!", (object)this.MethodInfo));
            }
            else
            {
                if (callback != null)
                {
                    result.ContinueWith((Action <Task>)(_ => callback((IAsyncResult)result)));
                }
                return((IAsyncResult)result);
            }
        }
Example #6
0
        public void GetFiltersOverridesControllerFiltersWithMethodFilters()
        {
            // DevDiv 222988
            // See comment in ReflectedActionDescriptor.RemoveOverriddenFilters()

            // Arrange
            Controller                controller = new OverriddenAttributeController();
            ControllerContext         context    = new Mock <ControllerContext>().Object;
            MethodInfo                methodInfo = typeof(OverriddenAttributeController).GetMethod("SomeMethod");
            ReflectedActionDescriptor ad         = GetActionDescriptor(methodInfo);

            // Act
            FilterInfo filters = ad.GetFilters();

            // Assert
            Assert.AreEqual(1, filters.ActionFilters.Count, "Wrong number of action filters.");
            Assert.AreEqual("Method", ((OutputCacheAttribute)filters.ActionFilters[0]).VaryByParam);
        }
Example #7
0
 public FilterRegisterConfigureItem(Type controllerType, ReflectedActionDescriptor actionDescriptor, Action <T> configureFilter, Type[] filterTypes)
     : base(controllerType, actionDescriptor, filterTypes)
 {
     ConfigureFilter = configureFilter;
     Filters         = () =>
     {
         if (FilterAttributesInstance != null)
         {
             return(FilterAttributesInstance);
         }
         return(FilterAttributesInstance = FilterTypes.Select(f =>
         {
             var attribute = Activator.CreateInstance(f) as FilterAttribute;
             configureFilter.Invoke(attribute as T);
             return attribute;
         }).ToList());
     };
 }
Example #8
0
        public static void AddDirectRouteFromMethod <T>(this RouteBase routeBase, Expression <Action <T> > methodCall)
        {
            RouteCollectionRoute route = (RouteCollectionRoute)routeBase;

            var method     = ((MethodCallExpression)methodCall.Body).Method;
            var attributes = method.GetCustomAttributes(false).OfType <IRouteInfoProvider>();

            var controllerDescriptor = new ReflectedAsyncControllerDescriptor(method.DeclaringType);
            var actionDescriptor     = new ReflectedActionDescriptor(method, method.Name, controllerDescriptor);

            foreach (var attribute in attributes)
            {
                var subRoute = new Route(attribute.Template, routeHandler: null);
                subRoute.SetTargetActionDescriptors(new ActionDescriptor[] { actionDescriptor });
                subRoute.SetTargetControllerDescriptor(controllerDescriptor);
                route.SubRoutes.Add(subRoute);
            }
        }
        public void TryCreateDescriptorReturnsDescriptorOnSuccess()
        {
            // Arrange
            MethodInfo           methodInfo = typeof(MyController).GetMethod("GoodActionMethod");
            ControllerDescriptor cd         = new Mock <ControllerDescriptor>().Object;

            // Act
            ReflectedActionDescriptor ad = ReflectedActionDescriptor.TryCreateDescriptor(
                methodInfo,
                "someName",
                cd
                );

            // Assert
            Assert.NotNull(ad);
            Assert.Same(methodInfo, ad.MethodInfo);
            Assert.Equal("someName", ad.ActionName);
            Assert.Same(cd, ad.ControllerDescriptor);
        }
        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);
            ReflectedActionDescriptor actionDescriptor = Assert.IsType <ReflectedActionDescriptor>(
                ad
                );

            Assert.Same(targetMethod, actionDescriptor.MethodInfo);
            Assert.Same(cd, ad.ControllerDescriptor);
        }
Example #11
0
        public void FixtureSetUp()
        {
            var controllerContext = new Mock <ControllerContext>();

            controllerContext.Setup(mock => mock.Controller).Returns(new TestController());
            _controllerContext    = controllerContext.Object;
            _controllerDescriptor = new Mock <ControllerDescriptor>().Object;

            _baseMethodInfo        = TestController.GetAction1MethodInfo <TestController>();
            _derivedMethodInfo     = TestController.GetAction1MethodInfo <TestControllerA>();
            _mostDerivedMethodInfo = TestController.GetAction1MethodInfo <TestControllerB>();
            _actionName            = _baseMethodInfo.Name;

            _reflectedActionDescriptor      = new ReflectedActionDescriptor(_baseMethodInfo, _actionName, _controllerDescriptor);
            _reflectedAsyncActionDescriptor = new ReflectedAsyncActionDescriptor(_baseMethodInfo, _baseMethodInfo, _actionName, _controllerDescriptor);
            _taskAsyncActionDescriptor      = new TaskAsyncActionDescriptor(_baseMethodInfo, _actionName, _controllerDescriptor);
            _derivedActionDescriptor        = new ReflectedActionDescriptor(_derivedMethodInfo, _actionName, _controllerDescriptor);
            _mostDerivedActionDescriptor    = new ReflectedActionDescriptor(_mostDerivedMethodInfo, _actionName, _controllerDescriptor);
        }
        protected static string CreateAmbiguousMatchList(
            IEnumerable <DirectRouteCandidate> candidates
            )
        {
            StringBuilder exceptionMessageBuilder = new StringBuilder();

            foreach (DirectRouteCandidate candidate in candidates)
            {
                MethodInfo method = null;

                ReflectedActionDescriptor reflectedActionDescriptor =
                    candidate.ActionDescriptor as ReflectedActionDescriptor;
                if (reflectedActionDescriptor == null)
                {
                    ReflectedAsyncActionDescriptor reflectedAsyncActionDescriptor =
                        candidate.ActionDescriptor as ReflectedAsyncActionDescriptor;
                    if (reflectedAsyncActionDescriptor != null)
                    {
                        method = reflectedAsyncActionDescriptor.AsyncMethodInfo;
                    }
                }
                else
                {
                    method = reflectedActionDescriptor.MethodInfo;
                }

                string controllerAction =
                    method == null
                        ? candidate.ActionDescriptor.ActionName
                        : Convert.ToString(method, CultureInfo.CurrentCulture);
                string controllerType = method.DeclaringType.FullName;

                exceptionMessageBuilder.AppendLine();
                exceptionMessageBuilder.AppendFormat(
                    CultureInfo.CurrentCulture,
                    MvcResources.ActionMethodSelector_AmbiguousMatchType,
                    controllerAction,
                    controllerType
                    );
            }

            return(exceptionMessageBuilder.ToString());
        }
        public void FindAction_ReturnsMethodWithActionSelectionAttributeIfMultipleMethodsMatchRequest()
        {
            // DevDiv Bugs 212062: If multiple action methods match a request, we should match only the methods with an
            // [ActionMethod] attribute since we assume those methods are more specific.

            // Arrange
            Type controllerType = typeof(SelectionAttributeController);
            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);

            // Act
            ActionDescriptorCreator creator          = selector.FindAction(null, "ShouldMatchMethodWithSelectionAttribute");
            ActionDescriptor        actionDescriptor = creator("someName", new Mock <ControllerDescriptor>().Object);

            // Assert
            Assert.IsInstanceOfType(actionDescriptor, typeof(ReflectedActionDescriptor));
            ReflectedActionDescriptor castActionDescriptor = (ReflectedActionDescriptor)actionDescriptor;

            Assert.AreEqual("MethodHasSelectionAttribute1", castActionDescriptor.MethodInfo.Name);
        }
Example #14
0
        /// <summary>
        /// Начинает выполнение асинхронной операции, описанной в action'e
        /// </summary>
        /// <param name="controllerContext">текущий контекст контроллера</param>
        /// <param name="parameters">параметры action'а</param>
        /// <param name="callback">делегат, который вызывается после завершения
        /// асинхронной операции</param>
        /// <param name="state">дополнительное состояние</param>
        /// <returns>возвращает асинхронную операцию в виде <see cref="IAsyncResult" /></returns>
        public override IAsyncResult BeginExecute(
            ControllerContext controllerContext, IDictionary <string, object> parameters, AsyncCallback callback, object state)
        {
            var rad    = new ReflectedActionDescriptor(_methodInfo, ActionName, ControllerDescriptor);
            var result = rad.Execute(controllerContext, parameters) as Task;

            if (result == null)
            {
                throw new InvalidOperationException(
                          String.Format("Метод {0} должен был вернуть Task!", _methodInfo));
            }

            if (callback != null)
            {
                result.ContinueWith(_ => callback(result));
            }

            return(result);
        }
        public T Invoke <T>(Expression <Func <T> > exp) where T : ActionResult
        {
            var methodCall       = (MethodCallExpression)exp.Body;
            var method           = methodCall.Method;
            var memberExpression = (MemberExpression)methodCall.Object;

            var getCallerExpression = Expression.Lambda <Func <object> >(memberExpression);
            var getCaller           = getCallerExpression.Compile();
            var ctrlr = (Controller)getCaller();

            var controllerDescriptor = new ReflectedControllerDescriptor(ctrlr.GetType());
            var actionDescriptor     = new ReflectedActionDescriptor(method, method.Name, controllerDescriptor);

            // OnActionExecuting

            ctrlr.ControllerContext = _controllerContext.Object;
            var actionExecutingContext = new ActionExecutingContext(ctrlr.ControllerContext, actionDescriptor, new Dictionary <string, object>());
            var onActionExecuting      = ctrlr.GetType().GetMethod("OnActionExecuting", BindingFlags.Instance | BindingFlags.NonPublic);

            onActionExecuting.Invoke(ctrlr, new object[] { actionExecutingContext });
            var actionResult = actionExecutingContext.Result;

            if (actionResult != null)
            {
                return((T)actionResult);
            }

            // call controller method

            var result = exp.Compile()();

            // OnActionExecuted
            var ctx2 = new ActionExecutedContext(ctrlr.ControllerContext, actionDescriptor, false, null)
            {
                Result = result
            };
            MethodInfo onActionExecuted = ctrlr.GetType().GetMethod("OnActionExecuted", BindingFlags.Instance | BindingFlags.NonPublic);

            onActionExecuted.Invoke(ctrlr, new object[] { ctx2 });

            return((T)ctx2.Result);
        }
Example #16
0
        public void ExecuteCallsMethodInfoOnSuccess()
        {
            // Arrange
            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext.Setup(c => c.Controller).Returns(new ConcatController());
            Dictionary <string, object> parameters = new Dictionary <string, object>()
            {
                { "a", "hello " },
                { "b", "world" }
            };

            ReflectedActionDescriptor ad = GetActionDescriptor(typeof(ConcatController).GetMethod("Concat"));

            // Act
            object result = ad.Execute(mockControllerContext.Object, parameters);

            // Assert
            Assert.Equal("hello world", result);
        }
 protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext, bool isLogined)
 {
     if (!filterContext.HttpContext.Request.IsAjaxRequest())
     {
         ReflectedActionDescriptor descriptor = filterContext.ActionDescriptor as ReflectedActionDescriptor;
         if (descriptor == null || descriptor.MethodInfo.ReturnType.Name == "ActionResult")
         {
             if (isLogined)
             {
                 filterContext.Result = new RedirectResult("/Home/Page404");
             }
             else
             {
                 filterContext.Result = new RedirectResult(string.Format("/Home/Login?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery));
             }
             return;
         }
     }
     filterContext.Result = new HttpUnauthorizedResult();
 }
        public void ExecuteThrowsIfParametersContainsNullForNonNullableParameter()
        {
            // Arrange
            ReflectedActionDescriptor   ad         = GetActionDescriptor(_int32EqualsIntMethod);
            Dictionary <string, object> parameters = new Dictionary <string, object>()
            {
                { "obj", null }
            };

            // Act & assert
            Assert.Throws <ArgumentException>(
                delegate
            {
                ad.Execute(new Mock <ControllerContext>().Object, parameters);
            },
                "The parameters dictionary contains a null entry for parameter 'obj' of non-nullable type 'System.Int32' for method 'Boolean Equals(Int32)' in 'System.Int32'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
                + Environment.NewLine
                + "Parameter name: parameters"
                );
        }
        public void ExecuteThrowsIfParametersContainsValueOfWrongTypeForParameter()
        {
            // Arrange
            ReflectedActionDescriptor   ad         = GetActionDescriptor(_int32EqualsIntMethod);
            Dictionary <string, object> parameters = new Dictionary <string, object>()
            {
                { "obj", "notAnInteger" }
            };

            // Act & assert
            Assert.Throws <ArgumentException>(
                delegate
            {
                ad.Execute(new Mock <ControllerContext>().Object, parameters);
            },
                "The parameters dictionary contains an invalid entry for parameter 'obj' for method 'Boolean Equals(Int32)' in 'System.Int32'. The dictionary contains a value of type 'System.String', but the parameter requires a value of type 'System.Int32'."
                + Environment.NewLine
                + "Parameter name: parameters"
                );
        }
        public void Test_Ninject_should_inject_for_Action_Attributes()
        {
            // Arrange
            var context = new ControllerContext {
                Controller = new ControllerWithActionAttribute()
            };
            var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType());
            var action           = context.Controller.GetType().GetMethod("ActionMethod");
            var actionDescriptor = new ReflectedActionDescriptor(action, "ActionMethod", controllerDescriptor);

            var mockKernel = new Mock <IKernel>();

            mockKernel.Setup(k => k.Inject(It.IsAny <MyFilterAttribute>())).Verifiable();
            var provider = new NinjectFilterAttributeFilterProvider(mockKernel.Object);

            // act
            provider.GetFilters(context, actionDescriptor);

            // assert
            mockKernel.Verify();
        }
Example #21
0
        public void GetFilters_IncludesAttributesOnActionMethod()
        {
            // Arrange
            var context = new ControllerContext {
                Controller = new ControllerWithActionAttribute()
            };
            var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType());
            var action           = context.Controller.GetType().GetMethod("MyActionMethod");
            var actionDescriptor = new ReflectedActionDescriptor(action, "MyActionMethod", controllerDescriptor);
            var provider         = new FilterAttributeFilterProvider();

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

            // Assert
            MyFilterAttribute attrib = filter.Instance as MyFilterAttribute;

            Assert.NotNull(attrib);
            Assert.Equal(FilterScope.Action, filter.Scope);
            Assert.Equal(1234, filter.Order);
        }
Example #22
0
        public void GetSelectorsWrapsSelectorAttributes()
        {
            // Arrange
            ControllerContext controllerContext = new Mock <ControllerContext>().Object;
            Mock <MethodInfo> mockMethod        = new Mock <MethodInfo>();

            Mock <ActionMethodSelectorAttribute> mockAttr = new Mock <ActionMethodSelectorAttribute>();

            mockAttr.Setup(attr => attr.IsValidForRequest(controllerContext, mockMethod.Object)).Returns(true).Verifiable();
            mockMethod.Setup(m => m.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true)).Returns(new ActionMethodSelectorAttribute[] { mockAttr.Object });

            ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);

            // Act
            ICollection <ActionSelector> selectors = ad.GetSelectors();
            bool executedSuccessfully = selectors.All(s => s(controllerContext));

            // Assert
            Assert.Single(selectors);
            Assert.True(executedSuccessfully);
            mockAttr.Verify();
        }
Example #23
0
        private static RouteEntry CreateRouteEntry(string routeTemplate)
        {
            var methodInfo           = typeof(TestController).GetMethod("Action");
            var controllerDescriptor = new ReflectedControllerDescriptor(typeof(TestController));
            var actionDescriptor     = new ReflectedActionDescriptor(
                methodInfo,
                "Action",
                controllerDescriptor);

            var route = new RouteBuilder2().BuildDirectRoute(
                routeTemplate,
                new RouteAttribute(),
                controllerDescriptor,
                actionDescriptor);

            var entry = new RouteEntry()
            {
                Route    = route,
                Template = routeTemplate,
            };

            return(entry);
        }
Example #24
0
        public void can_resolve_through_registry()
        {
            var controllerTypeConstraint = new ControllerTypeConstraint <TestController>();

            var method           = typeof(TestController).GetMethods().First(x => x.Name.Equals("ReturnNull") && x.GetParameters().Count() == 0);
            var actionDescriptor = new ReflectedActionDescriptor(method, "ReturnNull", new ReflectedControllerDescriptor(typeof(TestController)));

            var registry = new ActionFilterRegistry(new FluentMvcObjectFactory());

            registry.Add(new ControllerActionRegistryItem(typeof(TestFilter), controllerTypeConstraint, actionDescriptor, actionDescriptor.ControllerDescriptor));

            var proxyGenerator           = new ProxyGenerator();
            var interfaceProxyWithTarget = proxyGenerator.CreateClassProxy <TestController>();

            var controllerType = interfaceProxyWithTarget.GetType();

            var methodInfos           = controllerType.GetMethods();
            var proxyActionDescriptor = new ReflectedActionDescriptor(methodInfos.First(x => x.Name.Equals("ReturnNull") && x.GetParameters().Count() == 0), "ReturnNull", new ReflectedControllerDescriptor(controllerType));

            registry
            .CanSatisfy(new ControllerActionFilterSelector(null, proxyActionDescriptor, proxyActionDescriptor.ControllerDescriptor))
            .ShouldBeTrue();
        }
        public void IndexTest()
        {
            var errorMsg = "访问被拒绝,请通过微信客户端访问!";
            var filter   = new WeixinInternalRequestAttribute(errorMsg);

            {
                //模拟微信内置浏览器打开
                Init(weixinUserAgent);//初始化

                ActionDescriptor ad = new ReflectedActionDescriptor(target.GetType().GetMethod("Index"), "Index",
                                                                    new ReflectedAsyncControllerDescriptor(target.GetType()));
                ActionExecutingContext aec = new ActionExecutingContext(target.ControllerContext, ad,
                                                                        new Dictionary <string, object>());
                filter.OnActionExecuting(aec);

                Assert.IsNull(aec.Result);

                //下面的测试和UserAgent无关,只要Index可以被调用,都会有同样的结果
                ContentResult actual = target.Index();
                Assert.IsTrue(actual.Content.Contains("访问正常"));
            }

            {
                //模拟外部浏览器打开
                Init(outsideUserAgent);//初始化

                ActionDescriptor ad = new ReflectedActionDescriptor(target.GetType().GetMethod("Index"), "Index",
                                                                    new ReflectedAsyncControllerDescriptor(target.GetType()));
                ActionExecutingContext aec = new ActionExecutingContext(target.ControllerContext, ad,
                                                                        new Dictionary <string, object>());
                filter.OnActionExecuting(aec);

                Assert.IsNotNull(aec.Result);
                Assert.IsTrue(aec.Result is ContentResult);
                Assert.AreEqual(errorMsg, (aec.Result as ContentResult).Content);
            }
        }
            /// <summary>
            /// When testing MVC controllers, OnActionExecuted and OnActionExecuting functions are not get called.
            /// Code from: http://www.codeproject.com/Articles/623793/OnActionExecuting-and-OnActionExecuted-in-MVC-unit (The Code Project Open License (CPOL))
            /// </summary>
            private async static Task <T> InvokeAction <T>(Expression <Func <Task <T> > > actionCall, Controller controller) where T : ActionResult
            {
                var methodCall = (MethodCallExpression)actionCall.Body;
                var method     = methodCall.Method;

                ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
                ActionDescriptor     actionDescriptor     =
                    new ReflectedActionDescriptor(method, method.Name, controllerDescriptor);

                // OnActionExecuting

                var actionExecutingContext = new ActionExecutingContext(controller.ControllerContext,
                                                                        actionDescriptor, new Dictionary <string, object>());
                MethodInfo onActionExecuting = controller.GetType().GetMethod(
                    "OnActionExecuting", BindingFlags.Instance | BindingFlags.NonPublic);

                onActionExecuting.Invoke(controller, new object[] { actionExecutingContext });

                // call controller method

                T result = await actionCall.Compile()();

                // OnActionExecuted

                var actionExecutedContext = new ActionExecutedContext(controller.ControllerContext,
                                                                      actionDescriptor, false, null)
                {
                    Result = result
                };
                MethodInfo onActionExecuted = controller.GetType().GetMethod(
                    "OnActionExecuted", BindingFlags.Instance | BindingFlags.NonPublic);

                onActionExecuted.Invoke(controller, new object[] { actionExecutedContext });

                return((T)actionExecutedContext.Result);
            }
Example #27
0
        public void AttributeRouting_WithReflectedActionDescriptor()
        {
            // Arrange
            var controllerType = typeof(HomeController);
            var actionMethod   = controllerType.GetMethod("Index");

            var action = new ReflectedActionDescriptor();

            action.DisplayName      = "Microsoft.AspNet.Mvc.Routing.AttributeRoutingTest+HomeController.Index";
            action.MethodInfo       = actionMethod;
            action.RouteConstraints = new List <RouteDataActionConstraint>()
            {
                new RouteDataActionConstraint(AttributeRouting.RouteGroupKey, "group"),
            };
            action.AttributeRouteInfo          = new AttributeRouteInfo();
            action.AttributeRouteInfo.Template = "{controller}/{action}";

            action.RouteValueDefaults.Add("controller", "Home");
            action.RouteValueDefaults.Add("action", "Index");

            var expectedMessage =
                "The following errors occurred with attribute routing information:" + Environment.NewLine +
                Environment.NewLine +
                "For action: 'Microsoft.AspNet.Mvc.Routing.AttributeRoutingTest+HomeController.Index'" + Environment.NewLine +
                "Error: The attribute route '{controller}/{action}' cannot contain a parameter named '{controller}'. " +
                "Use '[controller]' in the route template to insert the value 'Home'.";

            var router   = CreateRouter();
            var services = CreateServices(action);

            // Act & Assert
            var ex = Assert.Throws <InvalidOperationException>(
                () => { AttributeRouting.CreateAttributeMegaRoute(router, services); });

            Assert.Equal(expectedMessage, ex.Message);
        }
        public void FixtureSetUp()
        {
            _baseControllerContext = new ControllerContext {
                Controller = new TestController()
            };
            _derivedControllerContext = new ControllerContext {
                Controller = new TestControllerA()
            };
            _mostDerivedControllerContext = new ControllerContext {
                Controller = new TestControllerB()
            };

            _baseMethodInfo        = TestController.GetAction1MethodInfo <TestController>();
            _derivedMethodInfo     = TestController.GetAction1MethodInfo <TestControllerA>();
            _mostDerivedMethodInfo = TestController.GetAction1MethodInfo <TestControllerB>();
            _actionName            = _baseMethodInfo.Name;

            _controllerDescriptor           = new Mock <ControllerDescriptor>().Object;
            _reflectedActionDescriptor      = new ReflectedActionDescriptor(_baseMethodInfo, _actionName, _controllerDescriptor);
            _reflectedAsyncActionDescriptor = new ReflectedAsyncActionDescriptor(_baseMethodInfo, _baseMethodInfo, _actionName, _controllerDescriptor);
            _taskAsyncActionDescriptor      = new TaskAsyncActionDescriptor(_baseMethodInfo, _actionName, _controllerDescriptor);
            _derivedActionDescriptor        = new ReflectedActionDescriptor(_derivedMethodInfo, _actionName, _controllerDescriptor);
            _mostDerivedActionDescriptor    = new ReflectedActionDescriptor(_mostDerivedMethodInfo, _actionName, _controllerDescriptor);
        }
Example #29
0
        /// <summary>
        /// Gets the site map item information.
        /// </summary>
        /// <returns></returns>
        // ReSharper disable once FunctionComplexityOverflow
        private static IEnumerable <PageInfo> GetPageInfos()
        {
            var items = new List <PageInfo>();

            try
            {
                foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(assembly => !assembly.GlobalAssemblyCache))
                {
                    Type[] assemblyTypes;

                    try { assemblyTypes = assembly.GetTypes(); }
                    catch (Exception) { continue; }

                    foreach (var controllerType in assemblyTypes)
                    {
                        if (!controllerType.IsSubclassOf(typeof(Controller)))
                        {
                            continue;
                        }

                        var  authorizeAttributeController    = controllerType.GetCustomAttributes(typeof(AuthorizeAttribute), true).Cast <AuthorizeAttribute>().FirstOrDefault();
                        bool?hasControllerAuthorizeAttribute = null; if (authorizeAttributeController != null)
                        {
                            hasControllerAuthorizeAttribute = true;
                        }

                        var  allowAnonymousAttributeController    = controllerType.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Cast <AllowAnonymousAttribute>().FirstOrDefault();
                        bool?hasControllerAllowAnonymousAttribute = null; if (allowAnonymousAttributeController != null)
                        {
                            hasControllerAllowAnonymousAttribute = true;
                        }

                        var mi = controllerType.GetMethods();

                        foreach (var m in mi)
                        {
                            if (!m.IsPublic || m.ReturnParameter == null)
                            {
                                continue;
                            }

                            var methodOk =
                                typeof(ActionResult).IsAssignableFrom(m.ReturnParameter.ParameterType) ||
                                typeof(Task <ActionResult>).IsAssignableFrom(m.ReturnParameter.ParameterType);

                            if (!methodOk)
                            {
                                continue;
                            }

                            var httpGetAttribute = m.GetCustomAttributes(typeof(HttpGetAttribute), true).Cast <HttpGetAttribute>().FirstOrDefault();
                            if (httpGetAttribute == null)
                            {
                                var httpPostAttribute = m.GetCustomAttributes(typeof(HttpPostAttribute), true).Cast <HttpPostAttribute>().FirstOrDefault();
                                if (httpPostAttribute != null)
                                {
                                    continue;            // no HttpPost actions
                                }
                            }

                            var  authorizeAttributeAction    = m.GetCustomAttributes(typeof(AuthorizeAttribute), true).Cast <AuthorizeAttribute>().FirstOrDefault();
                            var  authorizationRoles          = authorizeAttributeAction != null ? authorizeAttributeAction.Roles : "";
                            bool?hasActionAuthorizeAttribute = null; if (authorizeAttributeAction != null)
                            {
                                hasActionAuthorizeAttribute = true;
                            }

                            var  allowAnonymousAttributeAction    = m.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Cast <AllowAnonymousAttribute>().FirstOrDefault();
                            bool?hasActionAllowAnonymousAttribute = null; if (allowAnonymousAttributeAction != null)
                            {
                                hasActionAllowAnonymousAttribute = true;
                            }

                            var area = FindAreaForControllerType(controllerType);

                            var ignoreByPageInfoFactoryAttribute = m.GetCustomAttributes(typeof(IgnorePageInfoAttribute), true).Cast <IgnorePageInfoAttribute>().FirstOrDefault();
                            if (ignoreByPageInfoFactoryAttribute != null)
                            {
                                continue;
                            }

                            var allowRouteIfEqualsConfigurationAttributes      = m.GetCustomAttributes(typeof(AllowRouteIfEqualConfigAttribute), true).Cast <AllowRouteIfEqualConfigAttribute>();
                            var allowRouteIfEqualsConfigurationAttributesArray = allowRouteIfEqualsConfigurationAttributes as AllowRouteIfEqualConfigAttribute[] ?? allowRouteIfEqualsConfigurationAttributes.ToArray();

                            var include =
                                allowRouteIfEqualsConfigurationAttributesArray.Length <= 0 ||
                                allowRouteIfEqualsConfigurationAttributesArray.Any(allowRouteIfEqualsConfigurationAttribute => allowRouteIfEqualsConfigurationAttribute.IsAllowed());

                            if (!include)
                            {
                                continue;
                            }

                            var pageInfoAttribute      = m.GetCustomAttributes(typeof(PageInfoAttribute), true).Cast <PageInfoAttribute>().FirstOrDefault();
                            var metaInfoAttribute      = m.GetCustomAttributes(typeof(MetaInfoAttribute), true).Cast <MetaInfoAttribute>().FirstOrDefault();
                            var menuInfoAttribute      = m.GetCustomAttributes(typeof(MenuInfoAttribute), true).Cast <MenuInfoAttribute>().FirstOrDefault();
                            var routeInfoAttribute     = m.GetCustomAttributes(typeof(RouteInfoAttribute), true).Cast <RouteInfoAttribute>().FirstOrDefault();
                            var tagInfoAttribute       = m.GetCustomAttributes(typeof(TagInfoAttribute), true).Cast <TagInfoAttribute>().FirstOrDefault();
                            var relatedInfoAttributes  = m.GetCustomAttributes(typeof(RelatedInfoAttribute), true).Cast <RelatedInfoAttribute>();
                            var visibleInfoAttribute   = m.GetCustomAttributes(typeof(VisibleInfoAttribute), true).Cast <VisibleInfoAttribute>().FirstOrDefault();
                            var propertyInfoAttributes = m.GetCustomAttributes(typeof(CustomPropertyInfoAttribute), true).Cast <CustomPropertyInfoAttribute>();

                            if (pageInfoAttribute == null && metaInfoAttribute == null &&
                                menuInfoAttribute == null && routeInfoAttribute == null &&
                                tagInfoAttribute == null && relatedInfoAttributes == null &&
                                visibleInfoAttribute == null && propertyInfoAttributes == null)
                            {
                                continue;
                            }

                            if (pageInfoAttribute == null)
                            {
                                continue;
                            }

                            var controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
                            var actionDescriptor     = new ReflectedActionDescriptor(m, m.Name, controllerDescriptor);

                            var createController        = typeof(ControllerContextFactory).GetMethod("CreateController");
                            var genericCreateController = createController.MakeGenericMethod(controllerType);
                            var controllerContext       = ((Controller)genericCreateController.Invoke(null, new object[] { null })).ControllerContext;

                            bool?hasGlobalAuthorizeAttribute      = null;
                            bool?hasGlobalAllowAnonymousAttribute = null;

                            foreach (var provider in FilterProviders.Providers)
                            {
                                var filter = provider.GetFilters(controllerContext, actionDescriptor).FirstOrDefault(f => f.Instance is AuthorizeAttribute);
                                if (filter != null)
                                {
                                    hasGlobalAuthorizeAttribute = true;
                                }

                                filter = provider.GetFilters(controllerContext, actionDescriptor).FirstOrDefault(f => f.Instance is AllowAnonymousAttribute);
                                if (filter != null)
                                {
                                    hasGlobalAllowAnonymousAttribute = true;
                                }

                                if (hasGlobalAuthorizeAttribute.HasValue || hasGlobalAllowAnonymousAttribute.HasValue)
                                {
                                    break;
                                }
                            }

                            if (routeInfoAttribute == null)
                            {
                                routeInfoAttribute = new RouteInfoAttribute();
                            }
                            if (string.IsNullOrEmpty(routeInfoAttribute.Key))
                            {
                                routeInfoAttribute.Key = $"{area}{controllerType.Name.Replace("Controller", "")}{m.Name}";
                            }
                            if (string.IsNullOrEmpty(routeInfoAttribute.Url))
                            {
                                routeInfoAttribute.Url = $"{m.Name}/";
                            }

                            if (metaInfoAttribute == null)
                            {
                                metaInfoAttribute = new MetaInfoAttribute();
                            }
                            if (string.IsNullOrEmpty(metaInfoAttribute.Title))
                            {
                                metaInfoAttribute.Title = pageInfoAttribute.Title;
                            }
                            if (string.IsNullOrEmpty(metaInfoAttribute.Description))
                            {
                                metaInfoAttribute.Description = pageInfoAttribute.Title;
                            }
                            if (string.IsNullOrEmpty(metaInfoAttribute.Title) && string.IsNullOrEmpty(metaInfoAttribute.TitleResourceName))
                            {
                                metaInfoAttribute.TitleResourceType = pageInfoAttribute.TitleResourceType;
                                metaInfoAttribute.TitleResourceName = pageInfoAttribute.TitleResourceName;
                            }
                            if (string.IsNullOrEmpty(metaInfoAttribute.Description) && string.IsNullOrEmpty(metaInfoAttribute.DescriptionResourceName))
                            {
                                metaInfoAttribute.DescriptionResourceType = pageInfoAttribute.TitleResourceType;
                                metaInfoAttribute.DescriptionResourceName = pageInfoAttribute.TitleResourceName;
                            }

                            if (visibleInfoAttribute == null)
                            {
                                visibleInfoAttribute = new VisibleInfoAttribute();

                                int authorizeAttribute      = 0;
                                int allowAnonymousAttribute = 0;

                                if (hasGlobalAuthorizeAttribute.HasValue && hasGlobalAuthorizeAttribute.GetValueOrDefault(false))
                                {
                                    authorizeAttribute = 1;
                                }
                                if (hasControllerAuthorizeAttribute.HasValue && hasControllerAuthorizeAttribute.GetValueOrDefault(false))
                                {
                                    authorizeAttribute = 2;
                                }
                                if (hasActionAuthorizeAttribute.HasValue && hasActionAuthorizeAttribute.GetValueOrDefault(false))
                                {
                                    authorizeAttribute = 3;
                                }

                                if (hasGlobalAllowAnonymousAttribute.HasValue && hasGlobalAllowAnonymousAttribute.GetValueOrDefault(false))
                                {
                                    allowAnonymousAttribute = 1;
                                }
                                if (hasControllerAllowAnonymousAttribute.HasValue && hasControllerAllowAnonymousAttribute.GetValueOrDefault(false))
                                {
                                    allowAnonymousAttribute = 2;
                                }
                                if (hasActionAllowAnonymousAttribute.HasValue && hasActionAllowAnonymousAttribute.GetValueOrDefault(false))
                                {
                                    allowAnonymousAttribute = 3;
                                }

                                visibleInfoAttribute.Visible = authorizeAttribute < allowAnonymousAttribute;
                            }

                            items.Add(new PageInfo(
                                          m.Name,
                                          controllerType.Name.Replace("Controller", ""),
                                          area,
                                          controllerType,
                                          pageInfoAttribute,
                                          metaInfoAttribute,
                                          menuInfoAttribute,
                                          routeInfoAttribute,
                                          tagInfoAttribute,
                                          visibleInfoAttribute,
                                          relatedInfoAttributes,
                                          propertyInfoAttributes,
                                          authorizationRoles));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new DataMisalignedException("PageInfo attribute failure", ex);
            }

            return(items);
        }
Example #30
0
 public MyReflectedActionDescriptor(ReflectedActionDescriptor actionDescriptor)
     : base(actionDescriptor.MethodInfo, actionDescriptor.ActionName, actionDescriptor.ControllerDescriptor)
 {
     this.ActionExecutor = new ActionExecutor(actionDescriptor.MethodInfo);
 }
Example #31
0
        public void AttributeRouting_WithReflectedActionDescriptor()
        {
            // Arrange
            var controllerType = typeof(HomeController);
            var actionMethod = controllerType.GetMethod("Index");

            var action = new ReflectedActionDescriptor();
            action.DisplayName = "Microsoft.AspNet.Mvc.Routing.AttributeRoutingTest+HomeController.Index";
            action.MethodInfo = actionMethod;
            action.RouteConstraints = new List<RouteDataActionConstraint>()
            {
                new RouteDataActionConstraint(AttributeRouting.RouteGroupKey, "group"),
            };
            action.AttributeRouteTemplate = "{controller}/{action}";
            action.RouteValueDefaults.Add("controller", "Home");
            action.RouteValueDefaults.Add("action", "Index");

            var expectedMessage =
                "The following errors occurred with attribute routing information:" + Environment.NewLine +
                Environment.NewLine +
                "For action: 'Microsoft.AspNet.Mvc.Routing.AttributeRoutingTest+HomeController.Index'" + Environment.NewLine +
                "Error: The attribute route '{controller}/{action}' cannot contain a parameter named '{controller}'. " +
                "Use '[controller]' in the route template to insert the value 'Home'.";

            var router = CreateRouter();
            var services = CreateServices(action);

            // Act & Assert
            var ex = Assert.Throws<InvalidOperationException>(
                () => { AttributeRouting.CreateAttributeMegaRoute(router, services); });

            Assert.Equal(expectedMessage, ex.Message);
        }
Example #32
0
 private static bool ActionNamesAreEqual(ReflectedActionDescriptor selectorReflectedActionDescriptor, ReflectedActionDescriptor reflectedActionDescriptor)
 {
     return(reflectedActionDescriptor.MethodInfo.Name.Equals(selectorReflectedActionDescriptor.MethodInfo.Name, StringComparison.CurrentCultureIgnoreCase));
 }
        public void GetFilters_IncludesTypeAttributesFromDerivedTypeWhenMethodIsOnBaseClass()
        { // DDB #208062
            // Arrange
            var context = new ControllerContext { Controller = new DerivedController() };
            var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType());
            var action = context.Controller.GetType().GetMethod("MyActionMethod");
            var actionDescriptor = new ReflectedActionDescriptor(action, "MyActionMethod", controllerDescriptor);
            var provider = new FilterAttributeFilterProvider();

            // Act
            IEnumerable<Filter> filters = provider.GetFilters(context, actionDescriptor);

            // Assert
            Assert.NotNull(filters.Select(f => f.Instance).Cast<MyFilterAttribute>().Single());
        }