예제 #1
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;
        }
예제 #2
0
        public async Task ExecuteResultAsync_InvokesSignInAsyncOnConfiguredScheme()
        {
            // Arrange
            var principal = new ClaimsPrincipal();
            var authProperties = new AuthenticationProperties();
            var authenticationManager = new Mock<AuthenticationManager>();
            authenticationManager
                .Setup(c => c.SignInAsync("Scheme1", principal, authProperties))
                .Returns(TaskCache.CompletedTask)
                .Verifiable();
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(c => c.RequestServices).Returns(CreateServices());
            httpContext.Setup(c => c.Authentication).Returns(authenticationManager.Object);
            var result = new SignInResult("Scheme1", principal, authProperties);
            var routeData = new RouteData();

            var actionContext = new ActionContext(
                httpContext.Object,
                routeData,
                new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            authenticationManager.Verify();
        }
 public static void SetRouteData(this HttpContext httpContext, RouteData routeData)
 {
     httpContext.Features[typeof(IRoutingFeature)] = new RoutingFeatureMock
     {
         RouteData = routeData
     };
 }
예제 #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>
 public ActionContext(
     HttpContext httpContext,
     RouteData routeData,
     ActionDescriptor actionDescriptor)
     : this(httpContext, routeData, actionDescriptor, new ModelStateDictionary())
 {
 }
예제 #5
0
        public async Task ExecuteResultAsync_InvokesSignOutAsyncOnAuthenticationManager()
        {
            // Arrange
            var authenticationManager = new Mock<AuthenticationManager>();
            authenticationManager
                .Setup(c => c.SignOutAsync("", null))
                .Returns(TaskCache.CompletedTask)
                .Verifiable();
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(c => c.RequestServices).Returns(CreateServices());
            httpContext.Setup(c => c.Authentication).Returns(authenticationManager.Object);
            var result = new SignOutResult("", null);
            var routeData = new RouteData();

            var actionContext = new ActionContext(
                httpContext.Object,
                routeData,
                new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            authenticationManager.Verify();
        }
예제 #6
0
        private static ActionContext GetActionContext(HttpContext httpContext)
        {
            var routeData = new RouteData();
            routeData.Routers.Add(Mock.Of<IRouter>());

            return new ActionContext(httpContext,
                                    routeData,
                                    new ActionDescriptor());
        }
예제 #7
0
        public void RouteData_DefaultPropertyValues()
        {
            // Arrange & Act
            var routeData = new RouteData();

            // Assert
            Assert.Empty(routeData.DataTokens);
            Assert.Empty(routeData.Routers);
            Assert.Empty(routeData.Values);
        }
 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 static RouteData ResolveRouteData(IRouter router, LambdaExpression actionCallExpression)
        {
            var parsedRouteContext = Parse(actionCallExpression, considerParameterDescriptors: true);
            
            var routeData = new RouteData();

            parsedRouteContext.ActionArguments.ForEach(r => routeData.Values.Add(r.Key, r.Value.Value));
            routeData.Values["controller"] = parsedRouteContext.ControllerName;
            routeData.Values["action"] = parsedRouteContext.Action;

            routeData.Routers.Add(router);

            return 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;
                }
            }
        }
예제 #11
0
        public void RouteData_PushStateAndRestore_EmptyValues()
        {
            // Arrange
            var routeData = new RouteData();

            // Act
            var snapshot = routeData.PushState(null, new RouteValueDictionary(), new RouteValueDictionary());
            var copy = new RouteData(routeData);
            snapshot.Restore();

            // Assert
            Assert.Equal(routeData.DataTokens, copy.DataTokens);
            Assert.Equal(routeData.Routers, copy.Routers);
            Assert.Equal(routeData.Values, copy.Values);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ResolvedRouteContext"/> class.
 /// </summary>
 /// <param name="controllerType">Resolved controller type for the current route.</param>
 /// <param name="controllerName">Resolved controller name for the current route.</param>
 /// <param name="action">Resolved action name for the current route.</param>
 /// <param name="routeValues">Resolved dictionary of the action arguments for the current route.</param>
 /// <param name="routeData">Resolved HttpMessageHandler for the current route.</param>
 /// <param name="modelState">Resolved model state validation for the current route.</param>
 public ResolvedRouteContext(
     TypeInfo controllerType,
     string controllerName,
     string action,
     IDictionary<string, object> routeValues,
     RouteData routeData,
     ModelStateDictionary modelState)
 {
     this.IsResolved = true;
     this.ControllerType = controllerType;
     this.ControllerName = controllerName;
     this.Action = action;
     this.ActionArguments = routeValues.ToDetailedValues();
     this.RouteData = routeData;
     this.ModelState = modelState;
 }
        private string GetNameFromRouteContext(RouteData routeData)
        {
            string name = null;

            if (routeData.Values.Count > 0)
            {
                var routeValues = routeData.Values;

                object controller;
                routeValues.TryGetValue("controller", out controller);
                string controllerString = (controller == null) ? string.Empty : controller.ToString();

                if (!string.IsNullOrEmpty(controllerString))
                {
                    name = controllerString;

                    object action;
                    routeValues.TryGetValue("action", out action);
                    string actionString = (action == null) ? string.Empty : action.ToString();

                    if (!string.IsNullOrEmpty(actionString))
                    {
                        name += "/" + actionString;
                    }

                    if (routeValues.Keys.Count > 2)
                    {
                        // Add parameters
                        var sortedKeys = routeValues.Keys
                            .Where(key =>
                                !string.Equals(key, "controller", StringComparison.OrdinalIgnoreCase) &&
                                !string.Equals(key, "action", StringComparison.OrdinalIgnoreCase) &&
                                !string.Equals(key, TreeRouter.RouteGroupKey, StringComparison.OrdinalIgnoreCase))
                            .OrderBy(key => key, StringComparer.OrdinalIgnoreCase)
                            .ToArray();

                        if (sortedKeys.Length > 0)
                        {
                            string arguments = string.Join(@"/", sortedKeys);
                            name += " [" + arguments + "]";
                        }
                    }
                }
            }

            return name;
        }
예제 #14
0
        public void RouteData_PushStateAndRestore_NullRouteValueNotSet()
        {
            // Arrange
            var original = new RouteData();
            original.Values.Add("bleh", "16");

            var routeData = new RouteData(original);

            // Act
            var snapshot = routeData.PushState(
                null,
                new RouteValueDictionary(new { bleh = (string)null }),
                new RouteValueDictionary());
            snapshot.Restore();

            // Assert
            Assert.Equal(routeData.Values, original.Values);
        }
예제 #15
0
        public void RouteData_CopyConstructor()
        {
            // Arrange & Act
            var original = new RouteData();

            original.DataTokens.Add("data", "token");
            original.Routers.Add(Mock.Of<IRouter>());
            original.Values.Add("route", "value");

            var routeData = new RouteData(original);

            // Assert
            Assert.NotSame(routeData.DataTokens, original.DataTokens);
            Assert.Equal(routeData.DataTokens, original.DataTokens);
            Assert.NotSame(routeData.Routers, original.Routers);
            Assert.Equal(routeData.Routers, original.Routers);
            Assert.NotSame(routeData.Values, original.Values);
            Assert.Equal(routeData.Values, original.Values);
        }
예제 #16
0
        public void FormatFilter_ContextContainsFormat_InRouteAndQueryData()
        {
            // If the format is present in both route and query data, the one in route data wins

            // Arrange
            var mediaType = new StringSegment("application/json");
            var mockObjects = new MockObjects("json", FormatSource.RouteData);
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(c => c.Response).Returns(new Mock<HttpResponse>().Object);

            // Query contains xml
            httpContext.Setup(c => c.Request.Query.ContainsKey("format")).Returns(true);
            httpContext.Setup(c => c.Request.Query["format"]).Returns("xml");

            // Routedata contains json
            var data = new RouteData();
            data.Values.Add("format", "json");

            var ac = new ActionContext(httpContext.Object, data, new ActionDescriptor());

            var resultExecutingContext = new ResultExecutingContext(
                ac,
                new IFilterMetadata[] { },
                new ObjectResult("Hello!"),
                controller: new object());

            var resourceExecutingContext = new ResourceExecutingContext(
                ac,
                new IFilterMetadata[] { });

            var filter = new FormatFilter(mockObjects.OptionsManager);

            // Act
            filter.OnResourceExecuting(resourceExecutingContext);
            filter.OnResultExecuting(resultExecutingContext);

            // Assert
            var objectResult = Assert.IsType<ObjectResult>(resultExecutingContext.Result);
            Assert.Equal(1, objectResult.ContentTypes.Count);
            MediaTypeAssert.Equal(mediaType, objectResult.ContentTypes[0]);
        }
예제 #17
0
파일: RouteData.cs 프로젝트: Corays/Routing
        /// <summary>
        /// Creates a new <see cref="RouteData"/> instance with values copied from <paramref name="other"/>.
        /// </summary>
        /// <param name="other">The other <see cref="RouteData"/> instance to copy.</param>
        public RouteData(RouteData other)
        {
            if (other == null)
            {
                throw new ArgumentNullException(nameof(other));
            }

            // Perf: Avoid allocating collections unless we need to make a copy.
            if (other._routers != null)
            {
                _routers = new List<IRouter>(other.Routers);
            }

            if (other._dataTokens != null)
            {
                _dataTokens = new RouteValueDictionary(other._dataTokens);
            }

            if (other._values != null)
            {
                _values = new RouteValueDictionary(other._values);
            }
        }
예제 #18
0
        public async Task ChallengeResult_ExecuteNoSchemes()
        {
            // Arrange
            var result = new ChallengeResult(new string[] { }, null);

            var httpContext = new Mock<HttpContext>();
            httpContext.SetupGet(c => c.RequestServices).Returns(CreateServices().BuildServiceProvider());

            var auth = new Mock<AuthenticationManager>();
            httpContext.Setup(o => o.Authentication).Returns(auth.Object);

            var routeData = new RouteData();
            routeData.Routers.Add(Mock.Of<IRouter>());

            var actionContext = new ActionContext(httpContext.Object,
                                                  routeData,
                                                  new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            auth.Verify(c => c.ChallengeAsync((AuthenticationProperties)null), Times.Exactly(1));
        }
예제 #19
0
파일: RouteData.cs 프로젝트: Corays/Routing
            /// <summary>
            /// Creates a new <see cref="RouteDataSnapshot"/> for <paramref name="routeData"/>.
            /// </summary>
            /// <param name="routeData">The <see cref="RouteData"/>.</param>
            /// <param name="dataTokens">The data tokens.</param>
            /// <param name="routers">The routers.</param>
            /// <param name="values">The route values.</param>
            public RouteDataSnapshot(
                RouteData routeData,
                RouteValueDictionary dataTokens,
                IList<IRouter> routers,
                RouteValueDictionary values)
            {
                if (routeData == null)
                {
                    throw new ArgumentNullException(nameof(routeData));
                }

                _routeData = routeData;
                _dataTokens = dataTokens;
                _routers = routers;
                _values = values;
            }
예제 #20
0
 public RequestDelegate GetRequestHandler(HttpContext httpContext, RouteData routeData)
 {
     return(_requestDelegate);
 }
        // 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);
        }
예제 #22
0
        private static ActionContext GetActionContext(IServiceProvider serviceProvider, RouteData routeData)
        {
            // Set IServiceProvider properties because TemplateRoute gets services (e.g. an ILoggerFactory instance)
            // through the HttpContext.
            var httpContext = new DefaultHttpContext
            {
                RequestServices = serviceProvider,
            };

            if (routeData == null)
            {
                routeData = new RouteData
                {
                    Routers = { Mock.Of<IRouter>(), },
                };
            }

            return new ActionContext(httpContext, routeData, new ActionDescriptor());
        }
예제 #23
0
        private static RouteContext CreateRouteContext(string httpMethod)
        {
            var routeData = new RouteData();
            routeData.Routers.Add(new Mock<IRouter>(MockBehavior.Strict).Object);

            var serviceProvider = new ServiceCollection().BuildServiceProvider();

            var httpContext = new Mock<HttpContext>(MockBehavior.Strict);

            var request = new Mock<HttpRequest>(MockBehavior.Strict);
            request.SetupGet(r => r.Method).Returns(httpMethod);
            request.SetupGet(r => r.Path).Returns(new PathString());
            request.SetupGet(r => r.Headers).Returns(new HeaderDictionary());
            httpContext.SetupGet(c => c.Request).Returns(request.Object);
            httpContext.SetupGet(c => c.RequestServices).Returns(serviceProvider);

            return new RouteContext(httpContext.Object)
            {
                RouteData = routeData,
            };
        }
예제 #24
0
        /// <summary>
        /// Creates a new <see cref="RouteContext"/> for the provided <paramref name="httpContext"/>.
        /// </summary>
        /// <param name="httpContext">The <see cref="Http.HttpContext"/> associated with the current request.</param>
        public RouteContext(HttpContext httpContext)
        {
            HttpContext = httpContext;

            RouteData = new RouteData();
        }
예제 #25
0
            private ActionContext CreateMockActionContext(
                Mock<HttpContext> httpContext,
                string format,
                FormatSource? place)
            {
                var data = new RouteData();

                if (place == FormatSource.RouteData || place == FormatSource.RouteAndQueryData)
                {
                    data.Values.Add("format", format);
                    httpContext.Setup(c => c.Request.Query.ContainsKey("format")).Returns(false);
                }

                if (place == FormatSource.QueryData || place == FormatSource.RouteAndQueryData)
                {
                    httpContext.Setup(c => c.Request.Query.ContainsKey("format")).Returns(true);
                    httpContext.Setup(c => c.Request.Query["format"]).Returns(format);
                }
                else if (place == null && format == null)
                {
                    httpContext.Setup(c => c.Request.Query.ContainsKey("format")).Returns(false);
                }

                return new ActionContext(httpContext.Object, data, new ActionDescriptor());
            }
예제 #26
0
        public void RouteData_PushStateAndThenModify_WithInitialData()
        {
            // Arrange
            var original = new RouteData();
            original.DataTokens.Add("data", "token1");
            original.Routers.Add(Mock.Of<IRouter>());
            original.Values.Add("route", "value1");

            var routeData = new RouteData(original);

            // Act
            var snapshot = routeData.PushState(
                Mock.Of<IRouter>(),
                new RouteValueDictionary(new { route = "value2" }),
                new RouteValueDictionary(new { data = "token2" }));

            routeData.DataTokens.Add("data2", "token");
            routeData.Routers.Add(Mock.Of<IRouter>());
            routeData.Values.Add("route2", "value");

            var copy = new RouteData(routeData);
            snapshot.Restore();

            // Assert
            Assert.Equal(original.DataTokens, routeData.DataTokens);
            Assert.NotEqual(routeData.DataTokens, copy.DataTokens);
            Assert.Equal(original.Routers, routeData.Routers);
            Assert.NotEqual(routeData.Routers, copy.Routers);
            Assert.Equal(original.Values, routeData.Values);
            Assert.NotEqual(routeData.Values, copy.Values);
        }
예제 #27
0
        public void RouteData_PushStateAndThenModify()
        {
            // Arrange
            var routeData = new RouteData();

            // Act
            var snapshot = routeData.PushState(null, null, null);
            routeData.DataTokens.Add("data", "token");
            routeData.Routers.Add(Mock.Of<IRouter>());
            routeData.Values.Add("route", "value");

            var copy = new RouteData(routeData);
            snapshot.Restore();

            // Assert
            Assert.Empty(routeData.DataTokens);
            Assert.NotEqual(routeData.DataTokens, copy.DataTokens);
            Assert.Empty(routeData.Routers);
            Assert.NotEqual(routeData.Routers, copy.Routers);
            Assert.Empty(routeData.Values);
            Assert.NotEqual(routeData.Values, copy.Values);
        }
예제 #28
0
        private static ActionContext CreateActionContext(HttpContext context, IRouter router)
        {
            var routeData = new RouteData();
            routeData.Routers.Add(router);

            return new ActionContext(context, routeData, new ActionDescriptor());
        }
예제 #29
0
        private static ClientModelValidationContext GetValidationContextWithArea(string currentArea)
        {
            var serviceCollection = GetServiceCollection(localizerFactory: null);
            var serviceProvider = serviceCollection.BuildServiceProvider();
            var routeCollection = GetRouteCollectionWithArea(serviceProvider);
            var routeData = new RouteData
            {
                Routers =
                {
                    routeCollection,
                },
                Values =
                {
                    { "action", "Index" },
                    { "controller", "Home" },
                },
            };
            if (!string.IsNullOrEmpty(currentArea))
            {
                routeData.Values["area"] = currentArea;
            }

            var actionContext = GetActionContext(serviceProvider, routeData);

            var urlHelper = new UrlHelper(actionContext);
            var factory = new Mock<IUrlHelperFactory>(MockBehavior.Strict);
            factory
                .Setup(f => f.GetUrlHelper(actionContext))
                .Returns(urlHelper);

            // Make an IUrlHelperFactory available through the ActionContext.
            serviceCollection.AddSingleton<IUrlHelperFactory>(factory.Object);
            serviceProvider = serviceCollection.BuildServiceProvider();
            actionContext.HttpContext.RequestServices = serviceProvider;

            return new ClientModelValidationContext(
                 actionContext,
                 _metadata,
                 _metadataProvider,
                 new AttributeDictionary());
        }
예제 #30
0
        public async Task<ActionResult> Index(UserIndexOptions options, PagerParameters pagerParameters)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers))
            {
                return Unauthorized();
            }

            var siteSettings = await _siteService.GetSiteSettingsAsync();
            var pager = new Pager(pagerParameters, siteSettings.PageSize);

            // default options
            if (options == null)
            {
                options = new UserIndexOptions();
            }

            var users = _session.QueryAsync<User, UserIndex>();

            switch (options.Filter)
            {
                case UsersFilter.Approved:
                    //users = users.Where(u => u.RegistrationStatus == UserStatus.Approved);
                    break;
                case UsersFilter.Pending:
                    //users = users.Where(u => u.RegistrationStatus == UserStatus.Pending);
                    break;
                case UsersFilter.EmailPending:
                    //users = users.Where(u => u.EmailStatus == UserStatus.Pending);
                    break;
            }

            if (!string.IsNullOrWhiteSpace(options.Search))
            {
                users = users.Where(u => u.NormalizedUserName.Contains(options.Search) || u.NormalizedEmail.Contains(options.Search));
            }

            switch (options.Order)
            {
                case UsersOrder.Name:
                    users = users.OrderBy(u => u.NormalizedUserName);
                    break;
                case UsersOrder.Email:
                    users = users.OrderBy(u => u.NormalizedEmail);
                    break;
                case UsersOrder.CreatedUtc:
                    //users = users.OrderBy(u => u.CreatedUtc);
                    break;
                case UsersOrder.LastLoginUtc:
                    //users = users.OrderBy(u => u.LastLoginUtc);
                    break;
            }

            var count = await users.Count();

            var results = await users
                .Skip(pager.GetStartIndex())
                .Take(pager.PageSize)
                .List();

            // maintain previous route data when generating page links
            var routeData = new RouteData();
            routeData.Values.Add("Options.Filter", options.Filter);
            routeData.Values.Add("Options.Search", options.Search);
            routeData.Values.Add("Options.Order", options.Order);

            var pagerShape = New.Pager(pager).TotalItemCount(count).RouteData(routeData);

            var model = new UsersIndexViewModel
            {
                Users = results
                    .Select(x => new UserEntry { User = x })
                    .ToList(),
                Options = options,
                Pager = pagerShape
            };

            return View(model);
        }
예제 #31
0
        private ActionContext GetActionContext(string actionName = null)
        {
            var routeData = new RouteData();
            routeData.Values["action"] = actionName;

            return new ActionContext(new DefaultHttpContext(), routeData, new ControllerActionDescriptor() { ActionName = actionName });
        }