public void GetFormInfo()
        {
            var protector = new Mock<IDataProtector>();
            var protectorProvider = new Mock<IDataProtectionProvider>();
            protectorProvider.Setup(x => x.CreateProtector(It.IsAny<string>())).Returns(protector.Object);
            var surfaceRouteParams = $"{SurfaceFormHelper.ReservedAdditionalKeys.Controller}=mycontroller&{SurfaceFormHelper.ReservedAdditionalKeys.Action}=myaction&{SurfaceFormHelper.ReservedAdditionalKeys.Area}=myarea";
            protector.Setup(dataProtector => dataProtector.Protect(It.IsAny<byte[]>())).Returns(Encoding.UTF8.GetBytes(surfaceRouteParams));
            protector.Setup(dataProtector => dataProtector.Unprotect(It.IsAny<byte[]>())).Returns(Encoding.UTF8.GetBytes(surfaceRouteParams));
            var helper = new SurfaceFormHelper(Mock.Of<ILoggerFactory>(), protectorProvider.Object);
            var request = new Mock<HttpRequest>();
            request.Setup(httpRequest => httpRequest.Method).Returns("GET");
            request.Setup(httpRequest => httpRequest.Query).Returns(
                new FormCollection(new Dictionary<string, StringValues>
                {
                    {"ufprt", Convert.ToBase64String(Encoding.UTF8.GetBytes(surfaceRouteParams))}
                }));

            var httpCtxAccessor = new Mock<IHttpContextAccessor>();
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(context => context.Request).Returns(request.Object);
            httpCtxAccessor.Setup(accessor => accessor.HttpContext).Returns(httpContext.Object);
            var routeCtx = new RouteContext(httpContext.Object);

            var result = helper.GetFormInfo(routeCtx);

            Assert.Equal("mycontroller", result.ControllerName);
            Assert.Equal("myaction", result.ActionName);
            Assert.Equal("myarea", result.Area);
        }
        public void Activate_PopulatesServicesFromServiceContainer()
        {
            // Arrange
            var urlHelper = Mock.Of<IUrlHelper>();
            var service = new Mock<IServiceProvider>();
            service.Setup(s => s.GetService(typeof(IUrlHelper)))
                   .Returns(urlHelper);

            var httpContext = new Mock<HttpContext>();
            httpContext.SetupGet(c => c.RequestServices)
                       .Returns(service.Object);
            var routeContext = new RouteContext(httpContext.Object);
            var controller = new TestController();
            var context = new ActionContext(routeContext, new ActionDescriptor())
            {
                Controller = controller
            };
            var activator = new DefaultControllerActivator();

            // Act
            activator.Activate(controller, context);

            // Assert
            Assert.Same(urlHelper, controller.Helper);
        }
Beispiel #3
0
        public async virtual Task RouteAsync(RouteContext context)
        {
            for (var i = 0; i < Count; i++)
            {
                var route = this[i];

                var oldRouteData = context.RouteData;

                var newRouteData = new RouteData(oldRouteData);
                newRouteData.Routers.Add(route);

                try
                {
                    context.RouteData = newRouteData;

                    await route.RouteAsync(context);
                    if (context.IsHandled)
                    {
                        break;
                    }
                }
                finally
                {
                    if (!context.IsHandled)
                    {
                        context.RouteData = oldRouteData;
                    }
                }
            }
        }
        public void Activate_SetsPropertiesFromActionContextHierarchy()
        {
            // Arrange
            var httpRequest = Mock.Of<HttpRequest>();
            var httpContext = new Mock<HttpContext>();
            httpContext.SetupGet(c => c.Request)
                       .Returns(httpRequest);
            httpContext.SetupGet(c => c.RequestServices)
                       .Returns(Mock.Of<IServiceProvider>());
            var routeContext = new RouteContext(httpContext.Object);
            var controller = new TestController();
            var context = new ActionContext(routeContext, new ActionDescriptor())
            {
                Controller = controller
            };
            var activator = new DefaultControllerActivator();

            // Act
            activator.Activate(controller, context);

            // Assert
            Assert.Same(context, controller.ActionContext);
            Assert.Same(httpContext.Object, controller.HttpContext);
            Assert.Same(httpRequest, controller.GetHttpRequest());
        }
Beispiel #5
0
        public Task RouteAsync(RouteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            EnsureServices(context.HttpContext);

            var actionDescriptor = _actionSelector.Select(context);
            if (actionDescriptor == null)
            {
                _logger.NoActionsMatched();
                return TaskCache.CompletedTask;
            }

            if (actionDescriptor.RouteValueDefaults != null)
            {
                foreach (var kvp in actionDescriptor.RouteValueDefaults)
                {
                    if (!context.RouteData.Values.ContainsKey(kvp.Key))
                    {
                        context.RouteData.Values.Add(kvp.Key, kvp.Value);
                    }
                }

                // Removing RouteGroup from RouteValues to simulate the result of conventional routing
                context.RouteData.Values.Remove(TreeRouter.RouteGroupKey);
            }

            context.Handler = (c) => InvokeActionAsync(c, actionDescriptor);
            return TaskCache.CompletedTask;
        }
Beispiel #6
0
        public async Task RouteAsync(RouteContext context)
        {
            if (IsValidRequest(context.HttpContext))
            {
                try
                {
                    // Store the requested targetted action so that the OrchardMiddleware
                    // can continue with it once the tenant pipeline has been executed

                    if (_pipeline != null)
                    {
                        context.HttpContext.Items["orchard.Handler.Target"] = _target;
                        context.HttpContext.Items["orchard.Handler.RouteContext"] = context;

                        await _pipeline.Invoke(context.HttpContext);
                    }
                    else
                    {
                        await _target.RouteAsync(context);
                    }
                }
                catch (Exception ex)
                {
                    var logger = context.HttpContext.ApplicationServices.GetService<ILogger<TenantRoute>>();
                    logger.LogError("Error occured serving tenant route", ex);
                    throw;
                }
            }
        }
        public async Task Invoke(HttpContext httpContext)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Begin Routing Request");
            }

            var shellSettings = httpContext.RequestServices.GetService<ShellSettings>();
            var routerTable = httpContext.ApplicationServices.GetService<IRunningShellRouterTable>();

            var router = routerTable.GetOrAdd(
                shellSettings.Name, 
                name => httpContext.RequestServices.GetService<IRouteBuilder>().Build()
            );

            var context = new RouteContext(httpContext);
            context.RouteData.Routers.Add(router);

            await router.RouteAsync(context);

            if (!context.IsHandled)
            {
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("Request did not match any routes.");
                }

                await _next.Invoke(httpContext);
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("End Routing Request");
            }
        }
Beispiel #8
0
        public async Task RouteAsync(RouteContext context)
        {
            // Saving and restoring the original route data ensures that any values we
            // add won't 'leak' if action selection doesn't match.
            var oldRouteData = context.RouteData;

            // For diagnostics and link-generation purposes, routing should include
            // a list of IRoute instances that lead to the ultimate destination.
            // It's the responsibility of each IRouter to add the 'next' before 
            // calling it.
            var newRouteData = new RouteData(oldRouteData);
            newRouteData.Routers.Add(_next);

            var locale = GetLocale(context.HttpContext) ?? "en-US";
            newRouteData.Values.Add("locale", locale);

            try
            {
                context.RouteData = newRouteData;
                await _next.RouteAsync(context);
            }
            finally
            {
                if (!context.IsHandled)
                {
                    context.RouteData = oldRouteData;
                }
            }
        }
Beispiel #9
0
        public async Task RouteAsync(RouteContext context)
        {
            var request = context.HttpContext.Request;

            Uri uri;
            PathString remaining;
            if (!request.Path.StartsWithSegments(PathString.FromUriComponent("/" + _routePrefix), out remaining))
            {
                // Fallback to other routes.
                return;
            }

            uri = new Uri(remaining.ToString(), UriKind.Relative);
            
            context.HttpContext.ODataProperties().Model = _model;
            var parser = new ODataUriParser(_model, uri);
            var path = parser.ParsePath();
            context.HttpContext.ODataProperties().NewPath = path;
            context.HttpContext.ODataProperties().Path =
                context.HttpContext.ODataPathHandler().Parse(_model, "http://service-root/", remaining.ToString());
            context.HttpContext.ODataProperties().IsValidODataRequest = true;

            await m.RouteAsync(context);
            context.IsHandled = true;
        }
        public async Task RouteAsync(RouteContext context) {
            EnsureLoggers(context.HttpContext);
            using(_logger.BeginScope("SubdomainTemplateRoute.RouteAsync")) {
                var host = context.HttpContext.Request.Host.Value;

                if(host.Contains(":")) {
                    host = host.Substring(0, host.IndexOf(":"));
                }

                var values = _matcher.Match(host);
                if(values == null) {
                    _logger.Log(x => x.Verbose, x => x.LogVerbose(nameof(SubdomainTemplateRoute) + " " + Name + " - Host \"" + context.HttpContext.Request.Host + "\" did not match."));
                    return;
                }

                var oldRouteData = context.RouteData;
                var newRouteData = new RouteData(oldRouteData);

                newRouteData.DataTokens.MergeValues(DataTokens);
                newRouteData.Routers.Add(_target);
                newRouteData.Values.MergeValues(values);

                try {
                    context.RouteData = newRouteData;
                    await _innerRoute.RouteAsync(context);
                }
                finally {
                    if(!context.IsHandled) {
                        context.RouteData = oldRouteData;
                    }
                }
            }
        }
		public async Task RouteAsync(RouteContext context)
		{
			context.RouteData.Values["controller"] = context.RouteData.Values["controller"].ToString().Replace("-", "_");

			context.RouteData.Values["action"] = context.RouteData.Values["action"].ToString().Replace("-", "_");

			await _target.RouteAsync(context);
		}
Beispiel #12
0
        public async Task RouteAsync(RouteContext context)
        {
            context.RouteData.Routers.Add(_next);

            var locale = GetLocale(context.HttpContext) ?? "en-US";
            context.RouteData.Values.Add("locale", locale);

            await _next.RouteAsync(context);
        }
Beispiel #13
0
        public async Task RouteAsync(RouteContext context) {
            if (context.HttpContext.Request.Host.Value == _urlHost) {
                context.HttpContext.Items["orchard.Handler"] = new Func<Task>(async () => {
                    await _target.RouteAsync(context);
                });

                await _pipeline.Invoke(context.HttpContext);
            }
        }
        public async Task<ActionDescriptor> SelectAsync(RouteContext context)
        {
            if (context.HttpContext.ODataProperties().IsValidODataRequest)
            {
                return await Task.FromResult(_convention.SelectAction(context));
            }

            return await _selector.SelectAsync(context);
        }
 public async Task RouteAsync(RouteContext context)
 {
     var name = context.RouteData.Values["name"] as string;
     if (String.IsNullOrEmpty(name))
     {
         return;
     }
     await context.HttpContext.Response.WriteAsync($"Hi {name}!");
     context.IsHandled = true;
 }
        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);
        }
 public async Task Invoke(HttpContext httpContext)
 {
     var context = new RouteContext(httpContext);
     context.RouteData.Routers.Add(_router);
     await _router.RouteAsync(context);
     if (!context.IsHandled)
     {
         _logger.LogVerbose("Request did not match any routes.");
         await _next(httpContext);
     }
 }
Beispiel #18
0
        public async Task Invoke(HttpContext httpContext)
        {
            var rcontext = new RouteContext(httpContext);
            rcontext.RouteData.Routers.Add(_router);

            await _router.RouteAsync(rcontext);

            if (!rcontext.IsHandled)
            {
                await _next.Invoke(httpContext);
            }
        }
		public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
		{
			if (routeContext.RouteData.Values.ContainsKey(Name))
				return false;

			if (routeContext.RouteData.DataTokens.ContainsKey(Name))
				return false;

			if (routeContext.HttpContext.Request.Query.ContainsKey(Name))
				return false;

			return true;
		}
Beispiel #20
0
        /// <summary>
        /// Checks the request and query strings to see if it matches the definition of having a Surface controller
        /// posted/get value, if so, then we return a PostedDataProxyInfo object with the correct information.
        /// </summary>
        /// <param name="routeContext"></param>
        /// <returns></returns>
        public RouteDefinition GetFormInfo(RouteContext routeContext)
        {
            if (routeContext == null) throw new ArgumentNullException(nameof(routeContext));
            if (routeContext.HttpContext == null) throw new ArgumentNullException(nameof(routeContext) + ".HttpContext");
            if (routeContext.HttpContext.Request == null) throw new ArgumentNullException(nameof(routeContext) + ".HttpContext.Request");

            var encodedVal = GetRequestSurfaceToken(routeContext.HttpContext.Request);

            if (string.IsNullOrWhiteSpace(encodedVal)) return null;

            string decryptedString;
            try
            {
                decryptedString = Encoding.UTF8.GetString(_dataProtector.Unprotect(Convert.FromBase64String(encodedVal)));
            }
            catch (CryptographicException)
            {
                _logger.LogWarning("A value was detected in the ufprt parameter but Umbraco could not decrypt the string");
                return null;
            }

            var parsedQueryString = QueryHelpers.ParseQuery(decryptedString);
            var decodedParts = new Dictionary<string, string>();

            foreach (var key in parsedQueryString.Keys)
            {
                decodedParts[key] = parsedQueryString[key];
            }

            //validate all required keys exist

            var isValid = ValidateRequiredTokenParams(decodedParts);
            if (isValid == false) return null;

            foreach (var item in decodedParts.Where(x => new[] {
                ReservedAdditionalKeys.Controller,
                ReservedAdditionalKeys.Action,
                ReservedAdditionalKeys.Area }.Contains(x.Key) == false))
            {
                // Populate route with additional values which aren't reserved values so they eventually to action parameters
                routeContext.RouteData.Values[item.Key] = item.Value;
            }

            //return the proxy info without the surface id... could be a local controller.
            return new RouteDefinition
            {
                ControllerName = WebUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Controller).Value),
                ActionName = WebUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Action).Value),
                Area = WebUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Area).Value),
            };
        }
        public async Task ActionSelection_IndexNotSelectedByDefaultExceptGetAndPostVerbs(string verb)
        {
            // Arrange
            var routeContext = new RouteContext(GetHttpContext(verb));
            routeContext.RouteData.Values = new Dictionary<string, object>
            {
                { "controller", "RpcOnly" }
            };

            // Act
            var result = await InvokeActionSelector(routeContext);

            // Assert
            Assert.Equal(null, result);
        }
        public async Task ActionSelection_IndexSelectedByDefaultInAbsenceOfVerbOnlyMethod(string verb)
        {
            // Arrange
            var routeContext = new RouteContext(GetHttpContext(verb));
            routeContext.RouteData.Values = new Dictionary<string, object>
            {
                { "controller", "RpcOnly" }
            };

            // Act
            var result = await InvokeActionSelector(routeContext);

            // Assert
            Assert.Equal("Index", result.Name);
        }
        public async Task ActionSelection_PrefersVerbOnlyMethodOverIndex(string verb)
        {
            // Arrange
            var routeContext = new RouteContext(GetHttpContext(verb));
            routeContext.RouteData.Values = new Dictionary<string, object>
            {
                { "controller", "MixedRpcAndRest" }
            };

            // Act
            var result = await InvokeActionSelector(routeContext);

            // Assert
            Assert.Equal(verb, result.Name, StringComparer.OrdinalIgnoreCase);
        }
Beispiel #24
0
        public async Task RouteAsync(RouteContext context)
        {
            var lightcoreContext = context.HttpContext.LightcoreContext();

            if (lightcoreContext?.Item != null)
            {
                // Only try to run routes if Lightcore context is present, request pipeline could be aborted
                await _defaultHandler.RouteAsync(context);
            }
            else
            {
                // Make sure that the next middleware can run
                context.IsHandled = false;
            }
        }
Beispiel #25
0
        public async Task RouteAsync(RouteContext context) {
            if (IsValidRequest(context)) {
                context.HttpContext.Items["orchard.Handler"] = new Func<Task>(async () => {
                    try {
                        await _target.RouteAsync(context);
                    }
                    catch (Exception e) {
                        Logger.Error(e, e.Message);
                        throw;
                    }
                });

                await _pipeline.Invoke(context.HttpContext);
            }
        }
        public async Task Invoke(HttpContext httpContext) {
            Console.WriteLine("Begin Routing Request");

            var router = httpContext.RequestServices.GetService<IRouteBuilder>().Build();

            var context = new RouteContext(httpContext);
            context.RouteData.Routers.Add(router);

            await router.RouteAsync(context);

            if (!context.IsHandled) {
                await _next.Invoke(httpContext);
            }

            Console.WriteLine("End Routing Request");
        }
		public async Task RouteAsync(RouteContext context)
		{
			var version = $"v{context.RouteData.Values["apiversion"] ?? "0"}";

			var name = context.RouteData.Values["messagename"]?.ToString().Replace("/", ".");

			var body = await ReadBody(context.HttpContext);
			var msgItem = _protocolStringSerializer.Deserialize(body);

			var msg = new Message(name, msgItem);
			var result = await Handle(msg);

			var output = _protocolStringSerializer.SerializeToString(result);

			await context.HttpContext.Response.WriteAsync(output);
		}
Beispiel #28
0
        public async Task HttpMethodAttribute_ActionWithMultipleHttpMethodAttributes_ORsMultipleHttpMethods(string verb)
        {
            // Arrange
            var routeContext = new RouteContext(GetHttpContext(verb));
            routeContext.RouteData.Values = new Dictionary<string, object>()
            {
                { "controller", "HttpMethodAttributeTests_RestOnly" },
                { "action", "Put" }
            };

            // Act
            var result = await InvokeActionSelector(routeContext);

            // Assert
            Assert.Equal("Put", result.Name);
        }
Beispiel #29
0
        public async Task HttpMethodAttribute_ActionDecoratedWithHttpMethodAttribute_OverridesConvention(string verb)
        {
            // Arrange
            // Note no action name is passed, hence should return a null action descriptor.
            var routeContext = new RouteContext(GetHttpContext(verb));
            routeContext.RouteData.Values = new Dictionary<string, object>()
            {
                { "controller", "HttpMethodAttributeTests_RestOnly" },
            };

            // Act
            var result = await InvokeActionSelector(routeContext);

            // Assert
            Assert.Equal(null, result);
        }
        public async Task Invoke(HttpContext httpContext) {
            _logger.LogInformation("Begin Routing Request");

            var router = httpContext.RequestServices.GetService<IRouteBuilder>().Build();

            var context = new RouteContext(httpContext);
            context.RouteData.Routers.Add(router);

            await router.RouteAsync(context);

            if (!context.IsHandled) {
                _logger.LogInformation("Request did not match any routes.");
                await _next.Invoke(httpContext);
            }

            _logger.LogInformation("End Routing Request");
        }
Beispiel #31
0
 public Task RouteAsync(RouteContext context)
 {
     context.IsHandled = _isHandled;
     return(Task.FromResult <object>(null));
 }