예제 #1
0
        public override Boolean IsValidForRequest(RouteContext context, ActionDescriptor action)
        {
            if (context.HttpContext.Request.Headers == null)
                return false;

            return context.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
        }
        public void Select_AmbiguousActions_LogIsCorrect()
        {
            // Arrange
            var sink = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);

            var actions = new ActionDescriptor[]
            {
                new ActionDescriptor() { DisplayName = "A1" },
                new ActionDescriptor() { DisplayName = "A2" },
            };
            var selector = CreateSelector(actions, loggerFactory);

            var routeContext = CreateRouteContext("POST");
            var actionNames = string.Join(Environment.NewLine, actions.Select(action => action.DisplayName));
            var expectedMessage = "Request matched multiple actions resulting in " +
                $"ambiguity. Matching actions: {actionNames}";

            // Act
            Assert.Throws<AmbiguousActionException>(() => { selector.Select(routeContext); });

            // Assert
            Assert.Empty(sink.Scopes);
            Assert.Single(sink.Writes);
            Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString());
        }
        public void Select_PrefersActionWithConstraints()
        {
            // Arrange
            var actionWithConstraints = new ActionDescriptor()
            {
                ActionConstraints = new List<IActionConstraintMetadata>()
                {
                    new HttpMethodActionConstraint(new string[] { "POST" }),
                },
                Parameters = new List<ParameterDescriptor>(),
            };

            var actionWithoutConstraints = new ActionDescriptor()
            {
                Parameters = new List<ParameterDescriptor>(),
            };

            var actions = new ActionDescriptor[] { actionWithConstraints, actionWithoutConstraints };

            var selector = CreateSelector(actions);
            var context = CreateRouteContext("POST");

            // Act
            var action = selector.Select(context);

            // Assert
            Assert.Same(action, actionWithConstraints);
        }
예제 #4
0
        /// <summary>
        /// Creates a new <see cref="ActionContext"/>.
        /// </summary>
        /// <param name="httpContext">The <see cref="Http.HttpContext"/> for the current request.</param>
        /// <param name="routeData">The <see cref="AspNetCore.Routing.RouteData"/> for the current request.</param>
        /// <param name="actionDescriptor">The <see cref="Abstractions.ActionDescriptor"/> for the selected action.</param>
        /// <param name="modelState">The <see cref="ModelStateDictionary"/>.</param>
        public ActionContext(
            HttpContext httpContext,
            RouteData routeData,
            ActionDescriptor actionDescriptor,
            ModelStateDictionary modelState)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            if (routeData == null)
            {
                throw new ArgumentNullException(nameof(routeData));
            }

            if (actionDescriptor == null)
            {
                throw new ArgumentNullException(nameof(actionDescriptor));
            }

            if (modelState == null)
            {
                throw new ArgumentNullException(nameof(modelState));
            }

            HttpContext = httpContext;
            RouteData = routeData;
            ActionDescriptor = actionDescriptor;
            ModelState = modelState;
        }
예제 #5
0
        public void Accept_ForNoMatchingCandidates_SelectsTheFirstCandidate(string contentType)
        {
            // Arrange
            var constraint1 = new ConsumesAttribute("application/json", "text/xml");
            var action1 = new ActionDescriptor()
            {
                FilterDescriptors =
                    new List<FilterDescriptor>() { new FilterDescriptor(constraint1, FilterScope.Action) }
            };

            var constraint2 = new Mock<ITestConsumeConstraint>();
            var action2 = new ActionDescriptor()
            {
                FilterDescriptors =
                    new List<FilterDescriptor>() { new FilterDescriptor(constraint2.Object, FilterScope.Action) }
            };

            constraint2.Setup(o => o.Accept(It.IsAny<ActionConstraintContext>()))
                       .Returns(false);

            var context = new ActionConstraintContext();
            context.Candidates = new List<ActionSelectorCandidate>()
            {
                new ActionSelectorCandidate(action1, new [] { constraint1 }),
                new ActionSelectorCandidate(action2, new [] { constraint2.Object }),
            };

            context.CurrentCandidate = context.Candidates[0];
            context.RouteContext = CreateRouteContext(contentType: contentType);

            // Act & Assert
            Assert.True(constraint1.Accept(context));
        }
예제 #6
0
 /// <summary>
 /// Creates a new <see cref="ActionContext"/>.
 /// </summary>
 /// <param name="httpContext">The <see cref="Http.HttpContext"/> for the current request.</param>
 /// <param name="routeData">The <see cref="AspNetCore.Routing.RouteData"/> for the current request.</param>
 /// <param name="actionDescriptor">The <see cref="Abstractions.ActionDescriptor"/> for the selected action.</param>
 public ActionContext(
     HttpContext httpContext,
     RouteData routeData,
     ActionDescriptor actionDescriptor)
     : this(httpContext, routeData, actionDescriptor, new ModelStateDictionary())
 {
 }
예제 #7
0
        private MvcRouteHandler CreateMvcRouteHandler(
            ActionDescriptor actionDescriptor = null,
            IActionSelector actionSelector = null,
            IActionInvokerFactory invokerFactory = null,
            ILoggerFactory loggerFactory = null,
            object diagnosticListener = null)
        {
            var actionContextAccessor = new ActionContextAccessor();

            if (actionDescriptor == null)
            {
                var mockAction = new Mock<ActionDescriptor>();
                actionDescriptor = mockAction.Object;
            }

            if (actionSelector == null)
            {
                var mockActionSelector = new Mock<IActionSelector>();
                mockActionSelector
                    .Setup(a => a.SelectCandidates(It.IsAny<RouteContext>()))
                    .Returns(new ActionDescriptor[] { actionDescriptor });

                mockActionSelector
                    .Setup(a => a.SelectBestCandidate(It.IsAny<RouteContext>(), It.IsAny<IReadOnlyList<ActionDescriptor>>()))
                    .Returns(actionDescriptor);
                actionSelector = mockActionSelector.Object;
            }

            if (loggerFactory == null)
            {
                loggerFactory = NullLoggerFactory.Instance;
            }

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
            if (diagnosticListener != null)
            {
                diagnosticSource.SubscribeWithAdapter(diagnosticListener);
            }

            if (invokerFactory == null)
            {
                var mockInvoker = new Mock<IActionInvoker>();
                mockInvoker.Setup(i => i.InvokeAsync())
                    .Returns(Task.FromResult(true));

                var mockInvokerFactory = new Mock<IActionInvokerFactory>();
                mockInvokerFactory.Setup(f => f.CreateInvoker(It.IsAny<ActionContext>()))
                    .Returns(mockInvoker.Object);

                invokerFactory = mockInvokerFactory.Object;
            }

            return new MvcRouteHandler(
                invokerFactory,
                actionSelector,
                diagnosticSource,
                loggerFactory,
                actionContextAccessor);
        }
예제 #8
0
		public virtual object ApplyQueryOptions(object value, HttpRequest request, ActionDescriptor actionDescriptor, AssembliesResolver assembliesResolver)
		{
			var elementClrType = value is IEnumerable
				? TypeHelper.GetImplementedIEnumerableType(value.GetType())
				: value.GetType();

			var model = request.ODataProperties().Model;
			if (model == null)
			{
				throw Error.InvalidOperation(SRResources.QueryGetModelMustNotReturnNull);
			}

			var queryContext = new ODataQueryContext(
				model,
				elementClrType,
				assembliesResolver,
				request.ODataProperties().Path
				);

			var queryOptions = new ODataQueryOptions(queryContext, request, assembliesResolver);

			var enumerable = value as IEnumerable;
			if (enumerable == null)
			{
				// response is single entity.
				return value;
			}

			// response is a collection.
			var query = (value as IQueryable) ?? enumerable.AsQueryable();

			query = queryOptions.ApplyTo(query,
				new ODataQuerySettings
				{
					// TODO: If we are using SQL, set this to false
					// otherwise if it is entities in code then
					// set it to true
					HandleNullPropagation = 
					//HandleNullPropagationOption.True
					HandleNullPropagationOptionHelper.GetDefaultHandleNullPropagationOption(query),
					PageSize = actionDescriptor.PageSize(),
					SearchDerivedTypeWhenAutoExpand = true
				},
				AllowedQueryOptions.None);
			// Determine if this result should be a single entity
			
			if (ODataCountMediaTypeMapping.IsCountRequest(request))
			{
				long? count = request.ODataProperties().TotalCount;

				if (count.HasValue)
				{
					// Return the count value if it is a $count request.
					return count.Value;
				}
			}
			return query;
		}
        public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
        {
            if(routeContext.HttpContext.Request.Method != "POST")
            {
                return false;
            }

            var value = routeContext.HttpContext.Request.Form[_submitButtonName];
            return !string.IsNullOrEmpty(value);
        }
예제 #10
0
        /// <summary>
        /// Creates a new <see cref="ActionSelectorCandidate"/>.
        /// </summary>
        /// <param name="action">The <see cref="ActionDescriptor"/> representing a candidate for selection.</param>
        /// <param name="constraints">
        /// The list of <see cref="IActionConstraint"/> instances associated with <paramref name="action"/>.
        /// </param>
        public ActionSelectorCandidate(ActionDescriptor action, IReadOnlyList<IActionConstraint> constraints)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            Action = action;
            Constraints = constraints;
        }
 public static void AfterAction(
     this DiagnosticSource diagnosticSource,
     ActionDescriptor actionDescriptor,
     HttpContext httpContext,
     RouteData routeData)
 {
     if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.AfterAction"))
     {
         diagnosticSource.Write(
             "Microsoft.AspNetCore.Mvc.AfterAction",
             new { actionDescriptor, httpContext = httpContext, routeData = routeData });
     }
 }
        public void OnBeforeAction(ActionDescriptor actionDescriptor, HttpContext httpContext, RouteData routeData)
        {
            var telemetry = httpContext.RequestServices.GetService<RequestTelemetry>();
            if (telemetry != null && string.IsNullOrEmpty(telemetry.Name))
            {
                string name = this.GetNameFromRouteContext(routeData);

                if (!string.IsNullOrEmpty(name))
                {
                    name = httpContext.Request.Method + " " + name;
                    telemetry.Name = name;
                }
            }
        }
 private ControllerActionDescriptor GetActionDescriptorFromCache(MethodInfo methodInfo)
 {
     return(controllerActionDescriptorCache.GetOrAdd(methodInfo, _ =>
     {
         // we are only interested in controller actions
         ControllerActionDescriptor foundControllerActionDescriptor = null;
         IReadOnlyList <Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor> actionDescriptors = actionDescriptorsCollection.ActionDescriptors.Items;
         for (int i = 0; i < actionDescriptors.Count; i++)
         {
             Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor actionDescriptor = actionDescriptors[i];
             if (actionDescriptor is ControllerActionDescriptor descriptor && descriptor.MethodInfo == methodInfo)
             {
                 foundControllerActionDescriptor = descriptor;
                 break;
             }
         }
        public override bool IsValidForRequest(RouteContext context, ActionDescriptor action) {
            if (string.Equals(context.HttpContext.Request.Method, "GET", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(context.HttpContext.Request.Method, "HEAD", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(context.HttpContext.Request.Method, "DELETE", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(context.HttpContext.Request.Method, "TRACE", StringComparison.OrdinalIgnoreCase)) {
                return false;
            }

            if (string.IsNullOrEmpty(context.HttpContext.Request.ContentType)) {
                return false;
            }

            if (!context.HttpContext.Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) {
                return false;
            }

            return !string.IsNullOrEmpty(context.HttpContext.Request.Form[_name]);
        }
예제 #15
0
        /// <summary>
        /// Creates a new <see cref="ActionConstraintProviderContext"/>.
        /// </summary>
        /// <param name="context">The <see cref="Http.HttpContext"/> associated with the request.</param>
        /// <param name="action">The <see cref="ActionDescriptor"/> for which constraints are being created.</param>
        /// <param name="items">The list of <see cref="ActionConstraintItem"/> objects.</param>
        public ActionConstraintProviderContext(
            HttpContext context,
            ActionDescriptor action,
            IList<ActionConstraintItem> items)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            HttpContext = context;
            Action = action;
            Results = items;
        }
 public static MethodInfo GetMethodInfo(this ActionDescriptor actionDescriptor)
 {
     return(actionDescriptor.AsControllerActionDescriptor().MethodInfo);
 }
        // TODO need to pass the action name
        private static ActionContext GetActionContext(HttpContext httpContext)
        {
            var routeData = new RouteData();
            routeData.Values.Add(ActionRouter.ControllerKey, "Stormpath");
            routeData.Routers.Add(ActionRouter.Instance);

            var actionDescriptor = new ActionDescriptor()
            {
                RouteValues = new Dictionary<string, string>()
                {
                    [ActionRouter.ControllerKey] = "Stormpath",
                }
            };

            return new ActionContext(httpContext, routeData, actionDescriptor);
        }
 public static Type GetReturnType(this ActionDescriptor actionDescriptor)
 {
     return(actionDescriptor.GetMethodInfo().ReturnType);
 }
예제 #19
0
		internal static object SingleOrDefault(IQueryable queryable, ActionDescriptor actionDescriptor)
		{
			var enumerator = queryable.GetEnumerator();
			try
			{
				var result = enumerator.MoveNext() ? enumerator.Current : null;

				if (enumerator.MoveNext())
				{
					throw new InvalidOperationException(Error.Format(
						SRResources.SingleResultHasMoreThanOneEntity));
				}

				return result;
			}
			finally
			{
				// Fix for Issue #2097
				// Ensure any active/open database objects that were created
				// iterating over the IQueryable object are properly closed.
				var disposable = enumerator as IDisposable;
				if (disposable != null)
				{
					disposable.Dispose();
				}
			}
		}
예제 #20
0
        public void SelectBestCandidate_ActionConstraintFactory_ReturnsNull()
        {
            // Arrange
            var nullConstraint = new ActionDescriptor()
            {
                ActionConstraints = new List<IActionConstraintMetadata>()
                {
                    new ConstraintFactory()
                    {
                    },
                }
            };

            var actions = new ActionDescriptor[] { nullConstraint };

            var selector = CreateSelector(actions);
            var context = CreateRouteContext("POST");

            // Act
            var action = selector.SelectBestCandidate(context, actions);

            // Assert
            Assert.Same(action, nullConstraint);
        }
예제 #21
0
        private RouteContext CreateRouteContext(
            ActionDescriptor actionDescriptor = null,
            IActionSelector actionSelector = null,
            IActionInvokerFactory invokerFactory = null,
            ILoggerFactory loggerFactory = null,
            IOptions<MvcOptions> optionsAccessor = null,
            object diagnosticListener = null)
        {
            if (actionDescriptor == null)
            {
                var mockAction = new Mock<ActionDescriptor>();
                actionDescriptor = mockAction.Object;
            }

            if (actionSelector == null)
            {
                var mockActionSelector = new Mock<IActionSelector>();
                mockActionSelector.Setup(a => a.Select(It.IsAny<RouteContext>()))
                    .Returns(actionDescriptor);

                actionSelector = mockActionSelector.Object;
            }

            if (invokerFactory == null)
            {
                var mockInvoker = new Mock<IActionInvoker>();
                mockInvoker.Setup(i => i.InvokeAsync())
                    .Returns(Task.FromResult(true));

                var mockInvokerFactory = new Mock<IActionInvokerFactory>();
                mockInvokerFactory.Setup(f => f.CreateInvoker(It.IsAny<ActionContext>()))
                    .Returns(mockInvoker.Object);

                invokerFactory = mockInvokerFactory.Object;
            }

            if (loggerFactory == null)
            {
                loggerFactory = NullLoggerFactory.Instance;
            }

            if (optionsAccessor == null)
            {
                optionsAccessor = new TestOptionsManager<MvcOptions>();
            }

            var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
            if (diagnosticListener != null)
            {
                diagnosticSource.SubscribeWithAdapter(diagnosticListener);
            }

            var routingFeature = new RoutingFeature();

            var httpContext = new Mock<HttpContext>();
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IActionContextAccessor)))
                .Returns(new ActionContextAccessor());
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IActionSelector)))
                .Returns(actionSelector);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IActionInvokerFactory)))
                .Returns(invokerFactory);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(ILoggerFactory)))
                .Returns(loggerFactory);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(MvcMarkerService)))
                .Returns(new MvcMarkerService());
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(IOptions<MvcOptions>)))
                .Returns(optionsAccessor);
            httpContext
                .Setup(h => h.RequestServices.GetService(typeof(DiagnosticSource)))
                .Returns(diagnosticSource);
            httpContext
                .Setup(h => h.Features[typeof(IRoutingFeature)])
                .Returns(routingFeature);

            var routeContext = new RouteContext(httpContext.Object);
            routingFeature.RouteData = routeContext.RouteData;
            return routeContext;
        }
        private static HttpContext GetHttpContext(ActionDescriptor actionDescriptor)
        {
            var actionProvider = new Mock<IActionDescriptorProvider>(MockBehavior.Strict);

            actionProvider
                .SetupGet(p => p.Order)
                .Returns(-1000);

            actionProvider
                .Setup(p => p.OnProvidersExecuting(It.IsAny<ActionDescriptorProviderContext>()))
                .Callback<ActionDescriptorProviderContext>(c => c.Results.Add(actionDescriptor));

            actionProvider
                .Setup(p => p.OnProvidersExecuted(It.IsAny<ActionDescriptorProviderContext>()))
                .Verifiable();

            var context = new Mock<HttpContext>();
            context.Setup(o => o.RequestServices
                                .GetService(typeof(IEnumerable<IActionDescriptorProvider>)))
                   .Returns(new[] { actionProvider.Object });

            context.Setup(o => o.RequestServices
                               .GetService(typeof(IActionDescriptorCollectionProvider)))
                   .Returns(new ActionDescriptorCollectionProvider(context.Object.RequestServices));
            return context.Object;
        }
예제 #23
0
        public void SelectCandidates_NoMatch_ExcludesAttributeRoutedActions()
        {
            var actions = new ActionDescriptor[]
            {
                new ActionDescriptor()
                {
                    DisplayName = "A1",
                    RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        { "controller", "Home" },
                        { "action", "Index" }
                    },
                    AttributeRouteInfo = new AttributeRouteInfo()
                    {
                        Template = "/Home",
                    }
                },
            };

            var selector = CreateSelector(actions);

            var routeContext = CreateRouteContext("GET");
            routeContext.RouteData.Values.Add("controller", "Home");
            routeContext.RouteData.Values.Add("action", "Index");

            // Act
            var candidates = selector.SelectCandidates(routeContext);

            // Assert
            Assert.Empty(candidates);
        }
예제 #24
0
        public void SelectCandidates_MultipleMatches()
        {
            var actions = new ActionDescriptor[]
            {
                new ActionDescriptor()
                {
                    DisplayName = "A1",
                    RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        { "controller", "Home" },
                        { "action", "Index" }
                    },
                },
                new ActionDescriptor()
                {
                    DisplayName = "A2",
                    RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        { "controller", "Home" },
                        { "action", "Index" }
                    },
                },
            };

            var selector = CreateSelector(actions);

            var routeContext = CreateRouteContext("GET");
            routeContext.RouteData.Values.Add("controller", "Home");
            routeContext.RouteData.Values.Add("action", "Index");

            // Act
            var candidates = selector.SelectCandidates(routeContext);

            // Assert
            Assert.Equal(actions.ToArray(), candidates.ToArray());
        }
예제 #25
0
        public void SelectBestCandidate_Fallback_ToActionWithoutConstraints()
        {
            // Arrange
            var nomatch1 = new ActionDescriptor()
            {
                ActionConstraints = new List<IActionConstraintMetadata>()
                {
                    new BooleanConstraint() { Pass = true, Order = 0, },
                    new BooleanConstraint() { Pass = true, Order = 1, },
                    new BooleanConstraint() { Pass = false, Order = 2, },
                },
            };

            var nomatch2 = new ActionDescriptor()
            {
                ActionConstraints = new List<IActionConstraintMetadata>()
                {
                    new BooleanConstraint() { Pass = true, Order = 0, },
                    new BooleanConstraint() { Pass = true, Order = 1, },
                    new BooleanConstraint() { Pass = false, Order = 3, },
                },
            };

            var best = new ActionDescriptor();

            var actions = new ActionDescriptor[] { best, nomatch1, nomatch2 };

            var selector = CreateSelector(actions);
            var context = CreateRouteContext("POST");

            // Act
            var action = selector.SelectBestCandidate(context, actions);

            // Assert
            Assert.Same(action, best);
        }
예제 #26
0
 /// <summary>
 /// 是否控制器操作符
 /// </summary>
 /// <param name="actionDescriptor">操作描述符</param>
 public static bool IsControllerAction(this ActionDescriptor actionDescriptor) => actionDescriptor is ControllerActionDescriptor;
예제 #27
0
        public void SelectBestCandidate_ConstraintsInOrder_MultipleStages()
        {
            // Arrange
            var best = new ActionDescriptor()
            {
                ActionConstraints = new List<IActionConstraintMetadata>()
                {
                    new BooleanConstraint() { Pass = true, Order = 0, },
                    new BooleanConstraint() { Pass = true, Order = 1, },
                    new BooleanConstraint() { Pass = true, Order = 2, },
                },
            };

            var worst = new ActionDescriptor()
            {
                ActionConstraints = new List<IActionConstraintMetadata>()
                {
                    new BooleanConstraint() { Pass = true, Order = 0, },
                    new BooleanConstraint() { Pass = true, Order = 1, },
                    new BooleanConstraint() { Pass = true, Order = 3, },
                },
            };

            var actions = new ActionDescriptor[] { best, worst };

            var selector = CreateSelector(actions);
            var context = CreateRouteContext("POST");

            // Act
            var action = selector.SelectBestCandidate(context, actions);

            // Assert
            Assert.Same(action, best);
        }
예제 #28
0
        public void SelectBestCandidate_Ambiguous()
        {
            // Arrange
            var expectedMessage =
                "Multiple actions matched. " +
                "The following actions matched route data and had all constraints satisfied:" + Environment.NewLine +
                Environment.NewLine +
                "Ambiguous1" + Environment.NewLine +
                "Ambiguous2";

            var actions = new ActionDescriptor[]
            {
                CreateAction(area: null, controller: "Store", action: "Buy"),
                CreateAction(area: null, controller: "Store", action: "Buy"),
            };

            actions[0].DisplayName = "Ambiguous1";
            actions[1].DisplayName = "Ambiguous2";

            var selector = CreateSelector(actions);
            var context = CreateRouteContext("GET");

            context.RouteData.Values.Add("controller", "Store");
            context.RouteData.Values.Add("action", "Buy");

            // Act
            var ex = Assert.Throws<AmbiguousActionException>(() =>
            {
                selector.SelectBestCandidate(context, actions);
            });

            // Assert
            Assert.Equal(expectedMessage, ex.Message);
        }
 public static void BeforeOnActionExecuted(
     this DiagnosticSource diagnosticSource,
     ActionDescriptor actionDescriptor,
     ActionExecutedContext actionExecutedContext,
     IActionFilter filter)
 {
     if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.BeforeOnActionExecuted"))
     {
         diagnosticSource.Write(
             "Microsoft.AspNetCore.Mvc.BeforeOnActionExecuted",
             new
             {
                 actionDescriptor = actionDescriptor,
                 actionExecutedContext = actionExecutedContext,
                 filter = filter
             });
     }
 }
예제 #30
0
        public void SelectCandidates_SingleMatch()
        {
            var actions = new ActionDescriptor[]
            {
                new ActionDescriptor()
                {
                    DisplayName = "A1",
                    RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        { "controller", "Home" },
                        { "action", "Index" }
                    },
                },
                new ActionDescriptor()
                {
                    DisplayName = "A2",
                    RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        { "controller", "Home" },
                        { "action", "About" }
                    },
                },
            };

            var selector = CreateSelector(actions);

            var routeContext = CreateRouteContext("GET");
            routeContext.RouteData.Values.Add("controller", "Home");
            routeContext.RouteData.Values.Add("action", "Index");

            // Act
            var candidates = selector.SelectCandidates(routeContext);

            // Assert
            Assert.Collection(candidates, (a) => Assert.Same(actions[0], a));
        }
 public static void AfterOnResultExecuted(
     this DiagnosticSource diagnosticSource,
     ActionDescriptor actionDescriptor,
     ResultExecutedContext resultExecutedContext,
     IResultFilter filter)
 {
     if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.AfterOnResultExecuted"))
     {
         diagnosticSource.Write(
             "Microsoft.AspNetCore.Mvc.AfterOnResultExecuted",
             new
             {
                 actionDescriptor = actionDescriptor,
                 resultExecutedContext = resultExecutedContext,
                 filter = filter
             });
     }
 }
 public static bool IsControllerAction(this ActionDescriptor actionDescriptor)
 {
     return(actionDescriptor is ControllerActionDescriptor);
 }
        private static ActionDescriptor CreateActionDescriptor(string area, string controller, string action)
        {
            var actionDescriptor = new ActionDescriptor()
            {
                Name = string.Format("Area: {0}, Controller: {1}, Action: {2}", area, controller, action),
                RouteConstraints = new List<RouteDataActionConstraint>(),
            };

            actionDescriptor.RouteConstraints.Add(
                area == null ?
                new RouteDataActionConstraint("area", null) :
                new RouteDataActionConstraint("area", area));

            actionDescriptor.RouteConstraints.Add(
                controller == null ?
                new RouteDataActionConstraint("controller", null) :
                new RouteDataActionConstraint("controller", controller));

            actionDescriptor.RouteConstraints.Add(
                action == null ?
                new RouteDataActionConstraint("action", null) :
                new RouteDataActionConstraint("action", action));

            return actionDescriptor;
        }
 public static bool HasObjectResult(this ActionDescriptor actionDescriptor)
 {
     return(ActionResultHelper.IsObjectResult(actionDescriptor.GetReturnType()));
 }
예제 #35
0
        public void SelectBestCandidate_ConstraintsRejectAll_DifferentStages()
        {
            // Arrange
            var action1 = new ActionDescriptor()
            {
                ActionConstraints = new List<IActionConstraintMetadata>()
                {
                    new BooleanConstraint() { Pass = false, Order = 0 },
                    new BooleanConstraint() { Pass = true, Order = 1 },
                },
            };

            var action2 = new ActionDescriptor()
            {
                ActionConstraints = new List<IActionConstraintMetadata>()
                {
                    new BooleanConstraint() { Pass = true, Order = 0 },
                    new BooleanConstraint() { Pass = false, Order = 1 },
                },
            };

            var actions = new ActionDescriptor[] { action1, action2 };

            var selector = CreateSelector(actions);
            var context = CreateRouteContext("POST");

            // Act
            var action = selector.SelectBestCandidate(context, actions);

            // Assert
            Assert.Null(action);
        }
 public static bool IsPageAction(this ActionDescriptor actionDescriptor)
 {
     return(actionDescriptor is PageActionDescriptor);
 }
예제 #37
0
        public void SelectBestCandidate_CustomProvider()
        {
            // Arrange
            var actionWithConstraints = new ActionDescriptor()
            {
                ActionConstraints = new List<IActionConstraintMetadata>()
                {
                    new BooleanConstraintMarker() { Pass = true },
                }
            };

            var actionWithoutConstraints = new ActionDescriptor()
            {
                Parameters = new List<ParameterDescriptor>(),
            };

            var actions = new ActionDescriptor[] { actionWithConstraints, actionWithoutConstraints, };

            var selector = CreateSelector(actions);
            var context = CreateRouteContext("POST");

            // Act
            var action = selector.SelectBestCandidate(context, actions);

            // Assert
            Assert.Same(action, actionWithConstraints);
        }
예제 #38
0
 /// <summary>
 /// 获取方法信息
 /// </summary>
 /// <param name="actionDescriptor">操作描述符</param>
 public static MethodInfo GetMethodInfo(this ActionDescriptor actionDescriptor) => actionDescriptor.AsControllerActionDescriptor().MethodInfo;