Esempio n. 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;
        }
        public virtual void AddComposedFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor,
		                               FilterInfo filters)
        {
            var foundFilters = FilterLocators.Select(f => f.FindFilters(controllerContext, actionDescriptor));

            foundFilters.ForEach(f => AddFilters(filters, f));
        }
 protected void AddFilters(FilterInfo filters, FilterInfo mergeFilters)
 {
     mergeFilters.ActionFilters.ForEach(filters.ActionFilters.Add);
     mergeFilters.ExceptionFilters.ForEach(filters.ExceptionFilters.Add);
     mergeFilters.AuthorizationFilters.ForEach(filters.AuthorizationFilters.Add);
     mergeFilters.ResultFilters.ForEach(filters.ResultFilters.Add);
 }
Esempio n. 4
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="defaultFilters"></param>
        /// <param name="registeredFilters"></param>
        public MergedFilters(FilterInfo defaultFilters, FilterInfo registeredFilters)
        {
            DefaultFilters = defaultFilters;
            RegisteredFilters = registeredFilters;

            Merge();
        }
Esempio n. 5
0
        public void Matching_should_return_matched_filters()
        {
            var controllerContext = new ControllerContext
                                        {
                                            Controller = new Dummy1Controller()
                                        };

            var controllerDescriptor = new Mock<ControllerDescriptor>();
            controllerDescriptor.SetupGet(cd => cd.ControllerName).Returns("Dummy1");

            var actionDescriptor = new Mock<ActionDescriptor>();
            actionDescriptor.SetupGet(ad => ad.ControllerDescriptor).Returns(controllerDescriptor.Object);
            actionDescriptor.SetupGet(ad => ad.ActionName).Returns("Index");

            filterRegistryMock.Setup(x => x.Items)
                .Returns(new FilterRegistryItem[]
                             {
                                 new FilterRegistryActionItem<Dummy1Controller>(x => x.Index(), new Func<IMvcFilter>[] { () => new DummyFilter2(), () => new DummyFilter3() }),
                                 new FilterRegistryControllerItem<Dummy1Controller>(new Func<IMvcFilter>[] { () => new DummyFilter1(), () => new DummyFilter4() })
                             });

            var filters = new FilterInfo(provider.GetFilters(controllerContext, actionDescriptor.Object));

            Assert.IsType<DummyFilter1>(filters.AuthorizationFilters[0]);
            Assert.IsType<DummyFilter2>(filters.ActionFilters[0]);
            Assert.IsType<DummyFilter3>(filters.ResultFilters[0]);
            Assert.IsType<DummyFilter4>(filters.ExceptionFilters[0]);
        }
 public void BuildUp(FilterInfo filters)
 {
     CollectionExtensions.ForEach(filters.ActionFilters, Container.Kernel.InjectProperties);
     CollectionExtensions.ForEach(filters.AuthorizationFilters, Container.Kernel.InjectProperties);
     CollectionExtensions.ForEach(filters.ExceptionFilters, Container.Kernel.InjectProperties);
     CollectionExtensions.ForEach(filters.ResultFilters, Container.Kernel.InjectProperties);
 }
        public void OnActionExecuted(ActionExecutedContext filterContext) {

            // don't provide custom errors if the action has some custom code to handle exceptions
            if(!filterContext.ActionDescriptor.GetCustomAttributes(typeof(HandleErrorAttribute), false).Any()) {
                if (!filterContext.ExceptionHandled && filterContext.Exception != null) {
                    if (_exceptionPolicy.HandleException(this, filterContext.Exception)) {
                        var shape = _orchardServices.New.ErrorPage();
                        shape.Message = filterContext.Exception.Message;
                        shape.Exception = filterContext.Exception;

                        filterContext.ExceptionHandled = true;

                        // inform exception filters of the exception that was suppressed
                        var filterInfo = new FilterInfo();
                        foreach (var filterProvider in _filterProviders.Value) {
                            filterProvider.AddFilters(filterInfo);
                        }

                        var exceptionContext = new ExceptionContext(filterContext.Controller.ControllerContext, filterContext.Exception);
                        foreach (var exceptionFilter in filterInfo.ExceptionFilters) {
                            exceptionFilter.OnException(exceptionContext);
                        }

                        if (exceptionContext.ExceptionHandled) {
                            filterContext.Result = exceptionContext.Result;
                        }
                        else {
                            filterContext.Result = new ShapeResult(filterContext.Controller, shape);
                            filterContext.RequestContext.HttpContext.Response.StatusCode = 500;

                            // prevent IIS 7.0 classic mode from handling the 404/500 itself
                            filterContext.RequestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                        }
                    }
                }
            }

            if (filterContext.Result is HttpNotFoundResult) {
                var model = _orchardServices.New.NotFound();
                var request = filterContext.RequestContext.HttpContext.Request;
                var url = request.RawUrl;

                // If the url is relative then replace with Requested path
                model.RequestedUrl = request.Url.OriginalString.Contains(url) & request.Url.OriginalString != url ?
                    request.Url.OriginalString : url;

                // Dont get the user stuck in a 'retry loop' by
                // allowing the Referrer to be the same as the Request
                model.ReferrerUrl = request.UrlReferrer != null &&
                    request.UrlReferrer.OriginalString != model.RequestedUrl ?
                    request.UrlReferrer.OriginalString : null;

                filterContext.Result = new ShapeResult(filterContext.Controller, model);
                filterContext.RequestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;

                // prevent IIS 7.0 classic mode from handling the 404/500 itself
                filterContext.RequestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            }
        }
Esempio n. 8
0
 protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
 {
     // XXX: this is a terribl place to set these, but whatever
       _controllerContext = controllerContext;
       _actionDescriptor = actionDescriptor;
       _filterInfo = base.GetFilters(controllerContext, actionDescriptor);
       return _filterInfo;
 }
        public SimulatorActionInvoker(IMvcApplication mvcApplication, ActionExecutionContext actionExecutionContext)
        {
            _filterInfo = mvcApplication.GetFilterInfo(actionExecutionContext.ControllerContext,
                actionExecutionContext.ActionDescriptor);

            _mvcApplication = mvcApplication;
            _actionExecutionContext = actionExecutionContext;
        }
Esempio n. 10
0
 protected virtual void AddFilters(FilterInfo filterInfo) {
     if (this is IAuthorizationFilter)
         filterInfo.AuthorizationFilters.Add(this as IAuthorizationFilter);
     if (this is IActionFilter)
         filterInfo.ActionFilters.Add(this as IActionFilter);
     if (this is IResultFilter)
         filterInfo.ResultFilters.Add(this as IResultFilter);
     if (this is IExceptionFilter)
         filterInfo.ExceptionFilters.Add(this as IExceptionFilter);
 }
 protected void AddFilters(IGlobalFilter filter, FilterInfo filterInfo)
 {
     if (filter is IAuthorizationFilter)
         filterInfo.AuthorizationFilters.Add(filter as IAuthorizationFilter);
     if (filter is IActionFilter)
         filterInfo.ActionFilters.Add(filter as IActionFilter);
     if (filter is IResultFilter)
         filterInfo.ResultFilters.Add(filter as IResultFilter);
     if (filter is IExceptionFilter)
         filterInfo.ExceptionFilters.Add(filter as IExceptionFilter);
 }
 /// <summary>
 /// Injects the dependencies.
 /// </summary>
 /// <param name="filter">The filter.</param>
 public virtual void InjectDependencies(FilterInfo filter)
 {
     var serviceLocator = ServiceLocator;
     foreach (var f in filter.ActionFilters.Where(x => !(x is IController)))
         serviceLocator.Inject<IActionFilter>(f);
     foreach (var f in filter.AuthorizationFilters.Where(x => !(x is IController)))
         serviceLocator.Inject<IAuthorizationFilter>(f);
     foreach (var f in filter.ResultFilters.Where(x => !(x is IController)))
         serviceLocator.Inject<IResultFilter>(f);
     foreach (var f in filter.ExceptionFilters.Where(x => !(x is IController)))
         serviceLocator.Inject<IExceptionFilter>(f);
 }
 protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
 {
     var filterInfos = new List<FilterInfo> { base.GetFilters(controllerContext, actionDescriptor) };
     filterInfos.AddRange(ServiceLocator.Current.GetAllInstances<IConfigureFilter>()
         .Select(m => m.Registry.GetMatched(controllerContext, actionDescriptor)));
     var filterInfo = new FilterInfo();
     filterInfos.Each(m =>
     {
         m.ActionFilters.Each(filterInfo.ActionFilters.Add);
         m.AuthorizationFilters.Each(filterInfo.AuthorizationFilters.Add);
         m.ExceptionFilters.Each(filterInfo.ExceptionFilters.Add);
         m.ResultFilters.Each(filterInfo.ResultFilters.Add);
     });
     return filterInfo;
 }
Esempio n. 14
0
        /// <summary>
        /// Injects all filters of the specified filter info.
        /// </summary>
        /// <param name="filterInfo">The filter info.</param>
        public void Inject(FilterInfo filterInfo)
        {
            foreach (IActionFilter filter in filterInfo.ActionFilters.Where(f => f != null))
            {
                this.kernel.Inject(filter);
            }

            foreach (IAuthorizationFilter filter in filterInfo.AuthorizationFilters.Where(f => f != null))
            {
                this.kernel.Inject(filter);
            }

            foreach (IExceptionFilter filter in filterInfo.ExceptionFilters.Where(f => f != null))
            {
                this.kernel.Inject(filter);
            }

            foreach (IResultFilter filter in filterInfo.ResultFilters.Where(f => f != null))
            {
                this.kernel.Inject(filter);
            }            
        }
Esempio n. 15
0
		private void InitializeDelegateData(AuthorizationContext filterContext) {
			string typeName   = (string)filterContext.RouteData.Values[DelegateTypeNameParam],
			       methodName = (string)filterContext.RouteData.Values[DelegateMethodParam];
			Type t = container.FindType(typeName);
			var candidates = (  from mi in t.GetMethods((t.IsInterface ? BindingFlags.Instance : BindingFlags.Static) | BindingFlags.Public)
			                   where mi.Name.Equals(methodName, StringComparison.InvariantCultureIgnoreCase)
			                      && mi.GetCustomAttributes(typeof(AcceptVerbsAttribute), true).Cast<AcceptVerbsAttribute>().Any(attr => attr.IsValidForRequest(filterContext, mi))
			                  select mi
			                 ).ToList();
			if (candidates.Count > 1)
				throw new ArgumentException("More than one matching method");
			else if (candidates.Count == 0)
				throw new ArgumentException("No matching method. If the type is an interface, the method must be an instance method, if it's a class, it must be a public static method. The method must also be decorated with a suitable AcceptVerbsAttribute.");

			methodInfo = candidates[0];

			object[] customAttributes = methodInfo.GetCustomAttributes(true).ToArray();
			methodFilters = new FilterInfo();
			foreach (var a in customAttributes.OfType<IAuthorizationFilter>()) methodFilters.AuthorizationFilters.Add(a);
			foreach (var a in customAttributes.OfType<IActionFilter>()) methodFilters.ActionFilters.Add(a);
			foreach (var a in customAttributes.OfType<IResultFilter>()) methodFilters.ResultFilters.Add(a);
			foreach (var a in customAttributes.OfType<IExceptionFilter>()) methodFilters.ExceptionFilters.Add(a);
		}
 /// <summary>
 /// For each of the filters associated with the action, inject any dependencies for them.
 /// </summary>
 /// <param name="filters"></param>
 protected virtual void InjectDependenciesIntoFilters(FilterInfo filters)
 {
     filters.ActionFilters.ForEach(filter => ServiceLocator.Inject(filter));
     filters.AuthorizationFilters.ForEach(filter => ServiceLocator.Inject(filter));
     filters.ExceptionFilters.ForEach(filter => ServiceLocator.Inject(filter));
     filters.ResultFilters.ForEach(filter => ServiceLocator.Inject(filter));
 }
Esempio n. 17
0
        /// <summary>
        /// Merges a single <see cref="FilterInfo"/> to the base list.
        /// </summary>
        /// <param name="info"></param>
        protected virtual void MergeFilterInfo(FilterInfo info)
        {
            if (info == null) return;

            info.ActionFilters.ForEach(AddActionFilter);
            info.AuthorizationFilters.ForEach(AddAuthorizationFilter);
            info.ExceptionFilters.ForEach(AddExceptionFilter);
            info.ResultFilters.ForEach(AddResultFilter);
        }
Esempio n. 18
0
		protected override void OnAuthorization(AuthorizationContext filterContext) {
			if ((string)filterContext.RouteData.Values["action"] == "Delegate") {
				InitializeDelegateData(filterContext);
				foreach (var f in methodFilters.AuthorizationFilters) {
					f.OnAuthorization(filterContext);
					if (filterContext.Result != null)
						return;
				}
			}
			else
				methodFilters = new FilterInfo();
			base.OnAuthorization(filterContext);
		}
        public void InvokeActionThrowsIfBeginInvokeActionMethodThrowsUnhandledException() {
            // Arrange
            ActionResult actionResult = new ViewResult();
            FilterInfo filters = new FilterInfo();
            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;
            Dictionary<string,object> parameterValues = new Dictionary<string,object>();
            InvalidOperationException ex = new InvalidOperationException("Some exception text.");
            ControllerContext controllerContext = new ControllerContext() {
                Controller = new EmptyController() { ValidateRequest = false }
            };

            Mock<AsyncControllerActionInvokerHelper> mockHelper = new Mock<AsyncControllerActionInvokerHelper>() { CallBase = true };
            mockHelper.Expect(h => h.PublicGetControllerDescriptor(controllerContext)).Returns(cd).Verifiable();
            mockHelper.Expect(h => h.PublicFindAction(controllerContext, cd, "SomeAction")).Returns(ad).Verifiable();
            mockHelper.Expect(h => h.PublicGetFilters(controllerContext, ad)).Returns(filters).Verifiable();
            mockHelper.Expect(h => h.PublicInvokeAuthorizationFilters(controllerContext, filters.AuthorizationFilters, ad)).Returns(new AuthorizationContext()).Verifiable();
            mockHelper.Expect(h => h.PublicGetParameterValues(controllerContext, ad)).Returns(parameterValues).Verifiable();
            mockHelper.Expect(h => h.BeginInvokeActionMethodWithFilters(controllerContext, filters.ActionFilters, ad, parameterValues, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Throws(ex).Verifiable();
            mockHelper.Expect(h => h.PublicInvokeExceptionFilters(controllerContext, filters.ExceptionFilters, ex)).Returns(new ExceptionContext() { ExceptionHandled = false }).Verifiable();
            AsyncControllerActionInvokerHelper helper = mockHelper.Object;

            // Act & assert
            ExceptionHelper.ExpectException<InvalidOperationException>(
                delegate {
                    helper.BeginInvokeAction(controllerContext, "SomeAction", null, null);
                },
                @"Some exception text.");

            mockHelper.Verify();
        }
        public void InvokeActionThrowsIfRequestIsInvalid() {
            // Arrange
            ActionResult actionResult = new ViewResult();
            FilterInfo filters = new FilterInfo();
            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;
            HttpRequestValidationException ex = new HttpRequestValidationException();

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Expect(c => c.HttpContext.Request.RawUrl).Throws(ex);
            mockControllerContext.Expect(c => c.Controller).Returns(new EmptyController() { ValidateRequest = true });
            ControllerContext controllerContext = mockControllerContext.Object;

            Mock<AsyncControllerActionInvokerHelper> mockHelper = new Mock<AsyncControllerActionInvokerHelper>() { CallBase = true };
            mockHelper.Expect(h => h.PublicGetControllerDescriptor(controllerContext)).Returns(cd).Verifiable();
            mockHelper.Expect(h => h.PublicFindAction(controllerContext, cd, "SomeAction")).Returns(ad).Verifiable();
            mockHelper.Expect(h => h.PublicGetFilters(controllerContext, ad)).Returns(filters).Verifiable();
            mockHelper.Expect(h => h.PublicInvokeAuthorizationFilters(controllerContext, filters.AuthorizationFilters, ad)).Returns(new AuthorizationContext()).Verifiable();
            mockHelper.Expect(h => h.PublicInvokeExceptionFilters(controllerContext, filters.ExceptionFilters, ex)).Returns(new ExceptionContext() { ExceptionHandled = false }).Verifiable();
            AsyncControllerActionInvokerHelper helper = mockHelper.Object;

            // Act & assert
            ExceptionHelper.ExpectException<HttpRequestValidationException>(
                delegate {
                    helper.BeginInvokeAction(controllerContext, "SomeAction", null, null);
                });

            mockHelper.Verify();
        }
        public override FilterInfo GetFilters() {
            // For simplicity, we only consider filters on BeginFoo() since it is the entry point to the action

            // Enumerable.OrderBy() is a stable sort, so this method preserves scope ordering.
            FilterAttribute[] typeFilters = (FilterAttribute[])BeginMethod.ReflectedType.GetCustomAttributes(typeof(FilterAttribute), true /* inherit */);
            FilterAttribute[] methodFilters = (FilterAttribute[])BeginMethod.GetCustomAttributes(typeof(FilterAttribute), true /* inherit */);
            List<FilterAttribute> orderedFilters = RemoveOverriddenFilters(typeFilters.Concat(methodFilters)).OrderBy(attr => attr.Order).ToList();

            FilterInfo filterInfo = new FilterInfo();
            MergeFiltersIntoList(orderedFilters, filterInfo.ActionFilters);
            MergeFiltersIntoList(orderedFilters, filterInfo.AuthorizationFilters);
            MergeFiltersIntoList(orderedFilters, filterInfo.ExceptionFilters);
            MergeFiltersIntoList(orderedFilters, filterInfo.ResultFilters);
            return filterInfo;
        }
        public void InvokeActionWithAuthorizationFilterWhichShortCircuitsResult() {
            // Arrange
            ActionResult actionResult = new ViewResult();
            FilterInfo filters = new FilterInfo();
            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;
            ControllerContext controllerContext = new ControllerContext();

            bool invokeActionResultWasCalled = false;

            Mock<AsyncControllerActionInvokerHelper> mockHelper = new Mock<AsyncControllerActionInvokerHelper>() { CallBase = true };
            mockHelper.Expect(h => h.PublicGetControllerDescriptor(controllerContext)).Returns(cd).Verifiable();
            mockHelper.Expect(h => h.PublicFindAction(controllerContext, cd, "SomeAction")).Returns(ad).Verifiable();
            mockHelper.Expect(h => h.PublicGetFilters(controllerContext, ad)).Returns(filters).Verifiable();
            mockHelper.Expect(h => h.PublicInvokeAuthorizationFilters(controllerContext, filters.AuthorizationFilters, ad)).Returns(new AuthorizationContext() { Result = actionResult }).Verifiable();
            mockHelper
                .Expect(h => h.PublicInvokeActionResult(controllerContext, actionResult))
                .Callback(() => { invokeActionResultWasCalled = true; })
                .Verifiable();

            AsyncControllerActionInvokerHelper helper = mockHelper.Object;

            // Act & assert
            IAsyncResult asyncResult = helper.BeginInvokeAction(controllerContext, "SomeAction", null, null);
            Assert.IsFalse(invokeActionResultWasCalled, "InvokeActionResult() should not have been called yet.");
            bool retVal = helper.EndInvokeAction(asyncResult);

            Assert.IsTrue(retVal);
            mockHelper.Verify();
        }
 public void AddComposedFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor,
     FilterInfo filters)
 {
     _MaserFilterLocator.AddComposedFilters(controllerContext, actionDescriptor, filters);
 }
Esempio n. 24
0
        /// <summary>
        /// For each of the filters (excluding controllers) associated with the action, inject any dependencies for them.
        /// </summary>
        /// <param name="filters"></param>
        protected virtual void InjectDependenciesIntoFilters(FilterInfo filters)
        {
            filters.ActionFilters
                .Where(filter => !filter.IsType<IController>())
                .ForEach(filter => ServiceLocator.Inject(filter));

            filters.AuthorizationFilters
                .Where(filter => !filter.IsType<IController>())
                .ForEach(filter => ServiceLocator.Inject(filter));

            filters.ExceptionFilters
                .Where(filter => !filter.IsType<IController>())
                .ForEach(filter => ServiceLocator.Inject(filter));

            filters.ResultFilters
                .Where(filter => !filter.IsType<IController>())
                .ForEach(filter => ServiceLocator.Inject(filter));
        }
        /// <summary>
        /// Tests if authorization works for action.
        /// </summary>
        /// <param name="actionDescriptor">Action to test.</param>
        /// <param name="controllerContext">Controller context (including user) to test.</param>
        /// <returns>True/false if action is authorized.</returns>
        private static bool ActionIsAuthorized(ActionDescriptor actionDescriptor, ControllerContext controllerContext)
        {
            if (actionDescriptor == null)
            {
                // Action does not exist.
                return false;
            }

            // Get authorization context fo controller.
            AuthorizationContext authContext = new AuthorizationContext(controllerContext, actionDescriptor);

            // run each auth filter until on fails
            // performance could be improved by some caching
            var filters = FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor);
            FilterInfo filterInfo = new FilterInfo(filters);

            foreach (IAuthorizationFilter authFilter in filterInfo.AuthorizationFilters)
            {
                // Attempt authorization.
                authFilter.OnAuthorization(authContext);

                // If result is non-null, user is not authorized.
                if (authContext.Result != null)
                {
                    return false;
                }
            }

            // Assume user is authorized.
            return true;
        }
        public void InvokeActionWhereBeginInvokeActionMethodThrowsExceptionAndIsHandled() {
            // Arrange
            ActionResult actionResult = new ViewResult();
            FilterInfo filters = new FilterInfo();
            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;
            Dictionary<string, object> parameterValues = new Dictionary<string, object>();
            InvalidOperationException ex = new InvalidOperationException("Some exception text.");
            ControllerContext controllerContext = new ControllerContext() {
                Controller = new EmptyController() { ValidateRequest = false }
            };

            bool invokeActionResultWasCalled = false;

            Mock<AsyncControllerActionInvokerHelper> mockHelper = new Mock<AsyncControllerActionInvokerHelper>() { CallBase = true };
            mockHelper.Expect(h => h.PublicGetControllerDescriptor(controllerContext)).Returns(cd).Verifiable();
            mockHelper.Expect(h => h.PublicFindAction(controllerContext, cd, "SomeAction")).Returns(ad).Verifiable();
            mockHelper.Expect(h => h.PublicGetFilters(controllerContext, ad)).Returns(filters).Verifiable();
            mockHelper.Expect(h => h.PublicInvokeAuthorizationFilters(controllerContext, filters.AuthorizationFilters, ad)).Returns(new AuthorizationContext()).Verifiable();
            mockHelper.Expect(h => h.PublicGetParameterValues(controllerContext, ad)).Returns(parameterValues).Verifiable();
            mockHelper.Expect(h => h.BeginInvokeActionMethodWithFilters(controllerContext, filters.ActionFilters, ad, parameterValues, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Throws(ex).Verifiable();
            mockHelper.Expect(h => h.PublicInvokeExceptionFilters(controllerContext, filters.ExceptionFilters, ex)).Returns(new ExceptionContext() { ExceptionHandled = true, Result = actionResult }).Verifiable();
            mockHelper
                .Expect(h => h.PublicInvokeActionResult(controllerContext, actionResult))
                .Callback(() => { invokeActionResultWasCalled = true; })
                .Verifiable();

            AsyncControllerActionInvokerHelper helper = mockHelper.Object;

            // Act & assert
            IAsyncResult asyncResult = helper.BeginInvokeAction(controllerContext, "SomeAction", null, null);
            Assert.IsFalse(invokeActionResultWasCalled, "InvokeActionResult() should not yet have been called.");
            bool retVal = helper.EndInvokeAction(asyncResult);

            Assert.IsTrue(retVal);
            mockHelper.Verify();
        }
 public void AddFilters(FilterInfo filterInfo)
 {
 }
Esempio n. 28
0
 protected override FilterInfo GetFiltersForActionMethod(System.Reflection.MethodInfo methodInfo)
 {
     _filterInfo = base.GetFiltersForActionMethod(methodInfo);
       return _filterInfo;
 }
 void IFilterProvider.AddFilters(FilterInfo filterInfo)
 {
     AddFilters(filterInfo);
 }
Esempio n. 30
0
        /// <summary>
        /// 執行Action方法 主要動作
        /// Filter也在裡面做過濾
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="actionName"></param>
        /// <returns></returns>
        public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            Contract.Assert(controllerContext.RouteData != null);
            if (String.IsNullOrEmpty(actionName) && !controllerContext.RouteData.HasDirectRouteMatch())
            {
                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName");
            }

            ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);
            ActionDescriptor     actionDescriptor     = FindAction(controllerContext, controllerDescriptor, actionName);

            if (actionDescriptor != null)
            {
                FilterInfo filterInfo = GetFilters(controllerContext, actionDescriptor);

                try
                {
                    AuthenticationContext authenticationContext = InvokeAuthenticationFilters(controllerContext, filterInfo.AuthenticationFilters, actionDescriptor);

                    if (authenticationContext.Result != null)
                    {
                        // An authentication filter signaled that we should short-circuit the request. Let all
                        // authentication filters contribute to an action result (to combine authentication
                        // challenges). Then, run this action result.
                        AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge(
                            controllerContext, filterInfo.AuthenticationFilters, actionDescriptor,
                            authenticationContext.Result);
                        InvokeActionResult(controllerContext, challengeContext.Result ?? authenticationContext.Result);
                    }
                    else
                    {
                        AuthorizationContext authorizationContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor);
                        if (authorizationContext.Result != null)
                        {
                            // An authorization filter signaled that we should short-circuit the request. Let all
                            // authentication filters contribute to an action result (to combine authentication
                            // challenges). Then, run this action result.
                            AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge(
                                controllerContext, filterInfo.AuthenticationFilters, actionDescriptor,
                                authorizationContext.Result);
                            InvokeActionResult(controllerContext, challengeContext.Result ?? authorizationContext.Result);
                        }
                        else
                        {
                            if (controllerContext.Controller.ValidateRequest)
                            {
                                ValidateRequest(controllerContext);
                            }
                            //取得Action方法 執行參數
                            IDictionary <string, object> parameters = GetParameterValues(controllerContext, actionDescriptor);
                            //執行方法 和執行 IList<IActionFilter> 過濾器
                            ActionExecutedContext postActionContext = InvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters);

                            // The action succeeded. Let all authentication filters contribute to an action result (to
                            // combine authentication challenges; some authentication filters need to do negotiation
                            // even on a successful result). Then, run this action result.
                            AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge(
                                controllerContext, filterInfo.AuthenticationFilters, actionDescriptor,
                                postActionContext.Result);

                            InvokeActionResultWithFilters(controllerContext, filterInfo.ResultFilters,
                                                          challengeContext.Result ?? postActionContext.Result);
                        }
                    }
                }
                catch (ThreadAbortException)
                {
                    // This type of exception occurs as a result of Response.Redirect(), but we special-case so that
                    // the filters don't see this as an error.
                    throw;
                }
                catch (Exception ex)
                {
                    // something blew up, so execute the exception filters
                    // 錯誤處理過濾器
                    ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex);
                    //如果需要自己處理錯誤 exceptionContext.ExceptionHandled 設為true
                    if (!exceptionContext.ExceptionHandled)
                    {
                        throw;
                    }
                    InvokeActionResult(controllerContext, exceptionContext.Result);
                }

                return(true);
            }

            // notify controller that no method matched
            return(false);
        }