protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
        {
            var actionResult = (actionReturnValue as ActionResult)
                ?? _typedResultFactory.Build(controllerContext, actionReturnValue, actionDescriptor.ActionName);

            return actionResult;
        }
 private static ThemedConditionalAttribute GetThemedAttribute(ActionDescriptor descriptor)
 {
     return
         descriptor.GetCustomAttributes(typeof(ThemedConditionalAttribute), true).Concat(
             descriptor.ControllerDescriptor.GetCustomAttributes(typeof(ThemedConditionalAttribute), true)).
             OfType<ThemedConditionalAttribute>().FirstOrDefault();
 }
		/// <summary>
		/// Gets all Filter instances adapted from IActionFilter instances in IWindsorContainer
		/// </summary>
		/// <param name="controllerContext">ControllerContext</param>
		/// <param name="actionDescriptor">ActionDescriptor</param>
		/// <returns>IEnumerable of Filter instances</returns>
		public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
		{
			foreach (IActionFilter actionFilter in this._container.ResolveAll<IActionFilter>())
			{
				yield return new Filter(actionFilter, FilterScope.First, null);
			}
		}
        /// <summary>
        /// Gets all the filters that were registered with the <see cref="IFilterRegistry"/> instances.
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="actionDescriptor"></param>
        /// <returns></returns>
        public IEnumerable<System.Web.Mvc.Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) {
            var globalList = GetGlobalFilters();
            var controllerList = GetControllerFilters(controllerContext);
            var actionList = GetActionFilters(actionDescriptor);

            return globalList.Concat(controllerList).Concat(actionList);
        }
Exemple #5
0
 public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
 {
     return filterRegistry.Items.Where(item => item.IsMatching(controllerContext, actionDescriptor))
         .SelectMany(item => item.BuildFilters())
         .OrderBy(x => x.Order)
         .ToArray();
 }
        protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            var filterInfo = base.GetFilters(controllerContext, actionDescriptor);
            filterInfo.ExceptionFilters.Add(this._filter);

            return filterInfo;
        }
        public static ParameterDescriptor[] GetParameters(ActionDescriptor actionDescriptor, MethodInfo methodInfo, ref ParameterDescriptor[] parametersCache)
        {
            ParameterDescriptor[] parameters = LazilyFetchParametersCollection(actionDescriptor, methodInfo, ref parametersCache);

            // need to clone array so that user modifications aren't accidentally stored
            return (ParameterDescriptor[])parameters.Clone();
        }
        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));
        }
 private static ParameterDescriptor[] LazilyFetchParametersCollection(ActionDescriptor actionDescriptor, MethodInfo methodInfo, ref ParameterDescriptor[] parametersCache)
 {
     return DescriptorUtil.LazilyFetchOrCreateDescriptors<ParameterInfo, ParameterDescriptor>(
         cacheLocation: ref parametersCache,
         initializer: methodInfo.GetParameters,
         converter: parameterInfo => new ReflectedParameterDescriptor(parameterInfo, actionDescriptor));
 }
        protected override IEnumerable<FilterAttribute> GetActionAttributes(
            ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            //Ping controller lo excluyo
            if (controllerContext.Controller.GetType() == typeof(PingController)) return new List<FilterAttribute>();

            var attributes = new List<FilterAttribute>();
            attributes.AddRange(base.GetControllerAttributes(controllerContext, actionDescriptor));
            attributes.AddRange(base.GetActionAttributes(controllerContext, actionDescriptor));

            attributes.AddRange(_globalFilters);

            //By default add the AuthorizeItAttribute if is not present and not is anonymous
            //var attributesTypes = attributes.Select(x => x.GetType());
            //if(!attributesTypes.Contains(typeof(AnonymousAttribute))
            //    && !attributesTypes.Contains(typeof(AuthorizeItAttribute)))
            //    attributes.Add(new AuthorizeItAttribute());

            foreach (var attribute in attributes)
            {
                _container.BuildUp(attribute.GetType(), attribute);
            }

            return attributes;
        }
 public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
 {
     return from condition in _conditions
     select condition(controllerContext, actionDescriptor) into filter
     where filter != null
     select new Filter(filter, FilterScope.Global, null);
 }
        public bool IsSameAction(ActionDescriptor descriptor)
        {
            var desc = descriptor as ReflectedActionDescriptor;
            if (desc != null)
            {
                bool sameAction = ActionDescriptor.MethodInfo == desc.MethodInfo;
                if (sameAction)
                    return true;
            }
            ParameterDescriptor[] parameters1 = descriptor.GetParameters();

            bool same = descriptor.ControllerDescriptor.ControllerName.Equals(ActionDescriptor.ControllerDescriptor.ControllerName, StringComparison.OrdinalIgnoreCase) &&
                        descriptor.ActionName.Equals(ActionDescriptor.ActionName, StringComparison.OrdinalIgnoreCase) &&
                        (parameters1.Length == _actionParameterDescriptors.Length);

            if (same)
            {
                for (int i = parameters1.Length - 1; i >= 0; i--)
                {
                    if (parameters1[i].ParameterType == _actionParameterDescriptors[i].ParameterType)
                    {
                        continue;
                    }

                    same = false;
                    break;
                }
            }

            return same;
        }
Exemple #13
0
        private static bool ActionIsAuthorized(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            if (actionDescriptor == null) return false; // action does not exist so say yes - should we authorise this?!

            var authContext = new AuthorizationContext(controllerContext, actionDescriptor);

            // run each auth filter until one fails
            // performance could be improved by some caching
            var authorizeAttributes =
                FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor).Where(
                    x => x.Instance is AuthorizeActivityAttribute).Select(x => x.Instance);
            foreach (AuthorizeActivityAttribute authFilter in authorizeAttributes)
            {
                authFilter.OnAuthorization(authContext);

                if (authContext.Result != null) return false;
            }

            authorizeAttributes =
                FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor).Where(
                    x => x.Instance is AuthorizeAttribute).Select(x => x.Instance);
            foreach (AuthorizeAttribute authFilter in authorizeAttributes)
            {
                authFilter.OnAuthorization(authContext);

                if (authContext.Result != null) return false;
            }

            return true;
        }
 /// <summary>
 /// Create new descriptor
 /// </summary>
 /// <param name="actionDescriptor">Instance of the action descriptor</param>
 /// <param name="parameterName">Name of the parameter</param>
 /// <param name="parameterType">Type, mostly object</param>
 /// <param name="defaultValue">Default value, by default null</param>
 public DynamicParameterDescriptor(ActionDescriptor actionDescriptor, string parameterName, Type parameterType, object defaultValue)
 {
     this.actionDescriptor = actionDescriptor;
     this.parameterName = parameterName;
     this.parameterType = parameterType;
     this.defaultValue = defaultValue;
 }
        protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            var filterList = base.GetFilters(controllerContext, actionDescriptor);
            filterList.ResultFilters.Add(new ViewProviderFilter(actionDescriptor.ActionName));

            return filterList;
        }
        private static IEnumerable<FilterAttribute> ExecutedAttributesOf(ActionDescriptor actionDescriptor)
        {
            var actionCustomAttributes = actionDescriptor.GetCustomAttributes(inherit: true).OfType<FilterAttribute>().OrderByDescending(attribute => attribute.Order);
            var controllerCustomAttributes = actionDescriptor.ControllerDescriptor.GetCustomAttributes(inherit: true).OfType<FilterAttribute>().OrderByDescending(attribute => attribute.Order);

            return actionCustomAttributes.Concat(controllerCustomAttributes);
        }
        /// <summary>
        /// Gets the filters for the specified request and action.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="actionDescriptor">The action descriptor.</param>
        /// <returns>The filters.</returns>
        protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            FilterInfo filterInfo = base.GetFilters(controllerContext, actionDescriptor);
            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);
            }

            return filterInfo;
		}
        /// <summary>
        /// Retrieves information about the action filters.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="actionDescriptor">The action descriptor.</param>
        /// <returns>Information about the action filters.</returns>
        protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            //let the base class do the actual work as usual
            var filterInfo = base.GetFilters(controllerContext, actionDescriptor);

            //configure each collection of filters using the IApplicationContext
            foreach (IActionFilter filter in filterInfo.ActionFilters.Where(f => f != null))
            {
                _context.ConfigureObject(filter, filter.GetType().FullName);
            }

            foreach (IAuthorizationFilter filter in filterInfo.AuthorizationFilters.Where(f => f != null))
            {
                _context.ConfigureObject(filter, filter.GetType().FullName);
            }

            foreach (IExceptionFilter filter in filterInfo.ExceptionFilters.Where(f => f != null))
            {
                _context.ConfigureObject(filter, filter.GetType().FullName);
            }

            foreach (IResultFilter filter in filterInfo.ResultFilters.Where(f => f != null))
            {
                _context.ConfigureObject(filter, filter.GetType().FullName);
            }

            return filterInfo;
        }
        public IEnumerable<Filter> GetFilters(ControllerContext controllerContext,
            ActionDescriptor actionDescriptor)
        {
            if ((actionDescriptor.ControllerDescriptor.ControllerType ==
                    typeof(ProductController) &&
                (actionDescriptor.ActionName.Equals("Create", 
                    StringComparison.InvariantCultureIgnoreCase) ||
                actionDescriptor.ActionName.Equals("Edit", 
                    StringComparison.InvariantCultureIgnoreCase)) &&
                controllerContext.HttpContext.Request.HttpMethod == "POST") ||
                (actionDescriptor.ControllerDescriptor.ControllerType ==
                    typeof(ProductVariantController) &&
                (actionDescriptor.ActionName.Equals("Create",
                    StringComparison.InvariantCultureIgnoreCase) ||
                actionDescriptor.ActionName.Equals("Edit",
                    StringComparison.InvariantCultureIgnoreCase)) &&
                controllerContext.HttpContext.Request.HttpMethod == "POST"))
            {
                return new Filter[] 
                { 
                    new Filter(_actionFilter, FilterScope.Action, null)
                };
            };

            return new Filter[] { };
        }
        private string GetParamSignatureString(ActionDescriptor action)
        {
            var res = "(";

            ReflectedActionDescriptor aD = action as ReflectedActionDescriptor;

            foreach (var parameterDescriptor in aD.GetParameters())
            {
                res += parameterDescriptor.ParameterType.Name + " " + parameterDescriptor.ParameterName + ", ";
            }

            if (res == "(")
            {
                res += ")";
                return res;
            }

            if (res.Substring(res.Length - 2) == ", ")
            {
                res = res.Substring(0, res.Length - 2);
                res += ")";
            }

            return res;
        }
        public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
#if !DEBUG
            yield return new Filter(new RedirectToHttpsAttribute(), FilterScope.Global, App.HttpsRedirectOrder);
#endif
            yield return new Filter(new RequiresAllRoles("staff"), FilterScope.Global, App.ActiveAuthenticationOrder);
        }
 protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
 {
     if(!(actionReturnValue is ActionResult))
     {
         var controller = controllerContext.Controller;
         if(actionReturnValue is Result)
         {
             if(actionReturnValue == Result.Successfully)
             {
                 actionReturnValue = controller.Success();
             }
             else
             {
                 var result = actionReturnValue as IValueResult;
                 if(result.IsSucceed)
                 {
                     actionReturnValue = controller.Success(result.GetValue());
                 }
                 else actionReturnValue = controller.Faild(result.Message, result.Status);
             }
         }
         else
         {
             actionReturnValue = controller.Success(actionReturnValue);
         }
     }
     return base.CreateActionResult(controllerContext, actionDescriptor, actionReturnValue);
 }
Exemple #23
0
            protected override ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)
            {
                var uowParam = actionDescriptor.GetParameters().FirstOrDefault(x => x.ParameterType == typeof(IUnitOfWork));
                if (uowParam != null)
                {
                    var connectionKey = controllerContext.Controller.GetType().GetCustomAttribute<ConnectionKeyAttribute>();
                    if (connectionKey == null)
                        throw new ArgumentNullException("connectionKey");

                    using (var connection = SqlConnections.NewByKey(connectionKey.Value))
                    using (var uow = new UnitOfWork(connection))
                    {
                        parameters[uowParam.ParameterName] = uow;
                        var result = base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
                        uow.Commit();
                        return result;
                    }
                }

                var cnnParam = actionDescriptor.GetParameters().FirstOrDefault(x => x.ParameterType == typeof(IDbConnection));
                if (cnnParam != null)
                {
                    var connectionKey = controllerContext.Controller.GetType().GetCustomAttribute<ConnectionKeyAttribute>();
                    if (connectionKey == null)
                        throw new ArgumentNullException("connectionKey");

                    using (var cnn = SqlConnections.NewByKey(connectionKey.Value))
                    {
                        parameters[cnnParam.ParameterName] = cnn;
                        return base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
                    }
                }

                return base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
            }
        public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            //if (filterContext == null || filterContext.HttpContext == null)
            //     return new List<Filter>();

            string controllerName = controllerContext.RouteData.Values["controller"].ToString();
            Debug.WriteLine("Your Controller Name is " + controllerName);

            if (String.IsNullOrEmpty(controllerName))
                return new List<Filter>();

            //you are only looking for the Admin area Product controller - get out if the area key doesn't exist
            if (!controllerContext.RouteData.Values.ContainsKey("area"))
                return new List<Filter>();
            
            string areaName = controllerContext.RouteData.Values["area"].ToString();
            Debug.WriteLine("Your Area Name is " + areaName);
            if (String.IsNullOrEmpty(areaName))
                return new List<Filter>();

            //Note: you could also use controllerContext.RouteData.Values["action"].ToString();
            if (controllerName == "Product" && areaName == "Admin" && actionDescriptor.ActionName.Equals("Create", StringComparison.InvariantCultureIgnoreCase))
            {
                Debug.WriteLine("You got into the IF statement for Create");
                return new List<Filter>() { new Filter(this, FilterScope.Action, 0) };
            }


            return new List<Filter>();

        }
    CachePolicy IMvcCachePolicyProvider.CreateCachePolicy( ControllerContext context, ActionDescriptor action, IDictionary<string, object> parameters )
    {
      if ( context.IsChildAction )
        return null;

      return _provider.CreateCachePolicy( context.HttpContext );
    }
 /// <summary>
 /// Gets the key from the action descriptor.
 /// </summary>
 /// <param name="actionDescriptor">The action descriptor.</param>
 /// <returns>The key for the action.</returns>
 private static string GetKey(ActionDescriptor actionDescriptor)
 {
     return string.Format(
         "{0}.{1}",
         actionDescriptor.ControllerDescriptor.ControllerName,
         actionDescriptor.ActionName);
 }
 public ControllerAction Get(ActionDescriptor actionDescriptor)
 {
     string httpVerb = actionDescriptor.GetHttpVerb();
     return DB.ControllerActions.SingleOrDefault(r => r.Controller == actionDescriptor.ControllerDescriptor.ControllerName
         && r.Action == actionDescriptor.ActionName
         && r.HttpVerb == httpVerb);
 }
Exemple #28
0
    /// <summary>
    /// 获取缓存策略
    /// </summary>
    /// <param name="context">MVC 请求上下文</param>
    /// <param name="action">Action 信息</param>
    /// <param name="parameters">Action 参数</param>
    /// <returns>缓存策略</returns>
    protected override CachePolicy CreateCachePolicy( ControllerContext context, ActionDescriptor action, IDictionary<string, object> parameters )
    {

      if ( CachePolicyProvider != null )
        return CachePolicyProvider.CreateCachePolicy( context, action, parameters );



      var httpMethod = context.HttpContext.Request.HttpMethod;
      if ( !httpMethod.EqualsIgnoreCase( "get" ) && !httpMethod.EqualsIgnoreCase( "header" ) )//如果不是GET或Header请求,都不予缓存。
        return null;


      var provider = context.Controller as IMvcCachePolicyProvider;
      if ( provider == null )
      {
        var _provider = context.Controller as ICachePolicyProvider;
        if ( _provider != null )
          provider = new MvcCachePolicyProviderWrapper( _provider );
      }

      var policy = provider.CreateCachePolicy( context, action, parameters );

      if ( policy != null )
        return policy;



      return MvcEnvironment.CreateCachePolicy( context, action, parameters );

    }
        public void CreateRouteEntry_IfDirectRouteProviderReturnsRouteWithEmptyActionDescriptors_Throws()
        {
            // Arrange
            string areaPrefix = null;
            string controllerPrefix = null;
            Route route = new Route(url: null, routeHandler: null);
            route.DataTokens = new RouteValueDictionary();
            route.DataTokens.Add(RouteDataTokenKeys.Actions, new ActionDescriptor[0]);
            ActionDescriptor[] originalActions = route.GetTargetActionDescriptors();
            Assert.NotNull(originalActions); // Guard
            Assert.Equal(0, originalActions.Length); // Guard
            RouteEntry entry = new RouteEntry(name: null, route: route);
            IDirectRouteFactory factory = CreateStubRouteFactory(entry);
            ControllerDescriptor controllerDescriptor = CreateStubControllerDescriptor("IgnoreController");
            ActionDescriptor actionDescriptor = CreateStubActionDescriptor(controllerDescriptor, "IgnoreAction");
            IReadOnlyCollection<ActionDescriptor> actions = new ActionDescriptor[] { actionDescriptor };
            IInlineConstraintResolver constraintResolver =
                new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;

            // Act & Assert
            string expectedMessage = "The route does not have any associated action descriptors. Routing requires " +
                "that each direct route map to a non-empty set of actions.";
            Assert.Throws<InvalidOperationException>(() => DefaultDirectRouteProvider.CreateRouteEntry(areaPrefix,
                controllerPrefix, factory, actions, constraintResolver, targetIsAction: false), expectedMessage);
        }
        public void ShouldBeAbleToBuildWithFactoryUsingActionDescriptor(ActionDescriptor descriptor)
        { 
            var testMessage = new TestMessage().AsActionMessage(descriptor);

            Assert.Equal(descriptor.ActionName, testMessage.ActionName);
            Assert.Equal(descriptor.ControllerDescriptor.ControllerName, testMessage.ControllerName);
        }
Exemple #31
0
        protected virtual AuthorizationContext InvokeAuthorizationFilters(ControllerContext controllerContext, IList <IAuthorizationFilter> filters, ActionDescriptor actionDescriptor)
        {
            AuthorizationContext context = new AuthorizationContext(controllerContext, actionDescriptor);

            foreach (IAuthorizationFilter filter in filters)
            {
                filter.OnAuthorization(context);
                // short-circuit evaluation when an error occurs
                if (context.Result != null)
                {
                    break;
                }
            }

            return(context);
        }
Exemple #32
0
        protected virtual ActionExecutedContext InvokeActionMethodWithFilters(ControllerContext controllerContext, IList <IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary <string, object> parameters)
        {
            ActionExecutingContext       preContext   = new ActionExecutingContext(controllerContext, actionDescriptor, parameters);
            Func <ActionExecutedContext> continuation = () =>
                                                        new ActionExecutedContext(controllerContext, actionDescriptor, false /* canceled */, null /* exception */)
            {
                Result = InvokeActionMethod(controllerContext, actionDescriptor, parameters)
            };

            // need to reverse the filter list because the continuations are built up backward
            Func <ActionExecutedContext> thunk = filters.Reverse().Aggregate(continuation,
                                                                             (next, filter) => () => InvokeActionMethodFilter(filter, preContext, next));

            return(thunk());
        }
Exemple #33
0
        protected virtual ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
        {
            if (actionReturnValue == null)
            {
                return(new EmptyResult());
            }

            ActionResult actionResult = (actionReturnValue as ActionResult) ??
                                        new ContentResult {
                Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture)
            };

            return(actionResult);
        }
Exemple #34
0
        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);
                            }

                            IDictionary <string, object> parameters        = GetParameterValues(controllerContext, actionDescriptor);
                            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);
                    if (!exceptionContext.ExceptionHandled)
                    {
                        throw;
                    }
                    InvokeActionResult(controllerContext, exceptionContext.Result);
                }

                return(true);
            }

            // notify controller that no method matched
            return(false);
        }
Exemple #35
0
        protected virtual AuthenticationContext InvokeAuthenticationFilters(ControllerContext controllerContext,
                                                                            IList <IAuthenticationFilter> filters, ActionDescriptor actionDescriptor)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            Contract.Assert(controllerContext.HttpContext != null);
            IPrincipal            originalPrincipal = controllerContext.HttpContext.User;
            AuthenticationContext context           = new AuthenticationContext(controllerContext, actionDescriptor,
                                                                                originalPrincipal);

            foreach (IAuthenticationFilter filter in filters)
            {
                filter.OnAuthentication(context);
                // short-circuit evaluation when an error occurs
                if (context.Result != null)
                {
                    break;
                }
            }

            IPrincipal newPrincipal = context.Principal;

            if (newPrincipal != originalPrincipal)
            {
                Contract.Assert(context.HttpContext != null);
                context.HttpContext.User = newPrincipal;
                Thread.CurrentPrincipal  = newPrincipal;
            }

            return(context);
        }
Exemple #36
0
 protected virtual FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
 {
     return(new FilterInfo(_getFiltersThunk(controllerContext, actionDescriptor)));
 }
Exemple #37
0
        protected virtual ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary <string, object> parameters)
        {
            object       returnValue = actionDescriptor.Execute(controllerContext, parameters);
            ActionResult result      = CreateActionResult(controllerContext, actionDescriptor, returnValue);

            return(result);
        }
        protected virtual ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
        {
            ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

            return(actionDescriptor);
        }
Exemple #39
0
        protected virtual IDictionary <string, object> GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            Dictionary <string, object> parametersDict = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            ParameterDescriptor[] parameterDescriptors = actionDescriptor.GetParameters();

            foreach (ParameterDescriptor parameterDescriptor in parameterDescriptors)
            {
                parametersDict[parameterDescriptor.ParameterName] = GetParameterValue(controllerContext, parameterDescriptor);
            }
            return(parametersDict);
        }
Exemple #40
0
 protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
 {
     if (!(actionReturnValue is ActionResult))
     {
         if (actionReturnValue is Result)
         {
             if (actionReturnValue is SuccessfullyResult)
             {
                 actionReturnValue = new JsonNetResult(Successfully);
             }
             else
             {
                 var result = actionReturnValue as Result;
                 var value  = result.GetValue();
                 if (result.IsSucceed)
                 {
                     actionReturnValue = new JsonNetResult(value == null ? Successfully : new { Value = value });
                 }
                 else
                 {
                     actionReturnValue = new JsonNetResult(new { result.Message, result.Status });
                 }
             }
         }
         else
         {
             actionReturnValue = new JsonNetResult(actionReturnValue);
         }
     }
     return(base.CreateActionResult(controllerContext, actionDescriptor, actionReturnValue));
 }
Exemple #41
0
 IEnumerable <Filter> IFilterProvider.GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
 {
     return(this);
 }