/// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="response"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public IActionResult FromResponse <T>(T response, IRouteContext context) where T : Response
        {
            var result = new ResponseActionResult(context);

            response.Accept(result);
            return(result);
        }
Example #2
0
        public async Task InvokeRequest_OptionalParameter_Valid()
        {
            DefaultRpcInvoker invoker         = this.GetInvoker();
            IServiceProvider  serviceProvider = this.GetServiceProvider();
            IRouteContext     routeContext    = this.GetRouteContext <TestRouteClass>();


            //No params specified
            RpcRequest  stringRequest = RpcRequest.WithNoParameters("Optional", "1");
            RpcResponse response      = await invoker.InvokeRequestAsync(stringRequest, RpcPath.Default, routeContext);

            RpcResponse resultResponse = Assert.IsType <RpcResponse>(response);

            Assert.Null(resultResponse.Result);
            Assert.False(resultResponse.HasError);

            //Param is empty
            stringRequest = RpcRequest.WithParameterList("Optional", new object[0], "1");
            response      = await invoker.InvokeRequestAsync(stringRequest, RpcPath.Default, routeContext);

            resultResponse = Assert.IsType <RpcResponse>(response);
            Assert.Null(resultResponse.Result);
            Assert.False(resultResponse.HasError);


            //Param is a string
            stringRequest = RpcRequest.WithParameterList("Optional", new[] { JToken.FromObject("Test") }, "1");
            response      = await invoker.InvokeRequestAsync(stringRequest, RpcPath.Default, routeContext);

            resultResponse = Assert.IsType <RpcResponse>(response);
            Assert.NotNull(resultResponse.Result);
            Assert.Equal("Test", resultResponse.Result);
        }
Example #3
0
        private async Task <bool> IsAuthorizedAsync(RpcMethod rpcMethod, IRouteContext routeContext)
        {
            if (rpcMethod.AuthorizeDataListClass.Any() || rpcMethod.AuthorizeDataListMethod.Any())
            {
                if (rpcMethod.AllowAnonymousOnClass || rpcMethod.AllowAnonymousOnMethod)
                {
                    this.logger?.LogDebug("Skipping authorization. Allow anonymous specified for method.");
                }
                else
                {
                    this.logger?.LogDebug($"Running authorization for method.");
                    bool passedAuth = await this.CheckAuthorize(rpcMethod.AuthorizeDataListClass, routeContext);

                    if (passedAuth)
                    {
                        passedAuth = await this.CheckAuthorize(rpcMethod.AuthorizeDataListMethod, routeContext);
                    }
                    if (passedAuth)
                    {
                        this.logger?.LogDebug($"Authorization was successful for user '{routeContext.User.Identity.Name}'.");
                    }
                    else
                    {
                        this.logger?.LogInformation($"Authorization failed for user '{routeContext.User.Identity.Name}'.");
                        return(false);
                    }
                }
            }
            else
            {
                this.logger?.LogDebug("Skipping authorization. None configured for class or method.");
            }
            return(true);
        }
Example #4
0
        /// <summary>
        /// Finds the match.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public RouteMatch FindMatch(string url, IRouteContext context)
        {
            // TODO: lock for reading

            var           winnerPoints = 0;
            RouteMatch    winner       = null;
            DecoratedRule winnerule    = null;

            foreach (var rule in rules)
            {
                var match = new RouteMatch {
                    Name = rule.RouteName
                };
                var points = rule.Matches(url, context, match);

                if (points != 0 && points > winnerPoints)
                {
                    winnerPoints = points;
                    winner       = match;
                    winnerule    = rule;
                }
            }

            if (winner != null && winnerule.SelectionAction != null)
            {
                winnerule.SelectionAction(context, winner);
            }

            return(winner);
        }
Example #5
0
		public override int Matches(string url, IRouteContext context, RouteMatch match)
		{
			var points = base.Matches(url, context, match);
			
			if ((points == 0) || (string.Compare(restVerbResolver.Resolve(context.Request), requiredVerb, true) != 0))
				return 0;
			
			return points;
		}
		public HttpContextWrapper(HttpContext context, IRouteContext route, IViewFactory viewFactory)
		{
			this._context = context;
			this._request = new HttpRequestWrapper(context.Request);
			this._response = new HttpResponseWrapper(context.Response);
			this._session = new HttpSessionStateWrapper(context.Session);
			this.Route = route;
			this.ViewFactory = viewFactory;
		}
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="responseTask"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public Task <IActionResult> FromResponseAsync <T>(Task <T> responseTask, IRouteContext context) where T : Response
 {
     return(responseTask.ContinueWith(t => {
         if (t.IsFaulted)
         {
             return new StatusCodeResult(StatusCodes.Status500InternalServerError);
         }
         return FromResponse(t.Result, context);
     }));
 }
Example #8
0
        /// <summary>
        /// Determines if the specified URL matches the
        /// routing rule.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="context">The context</param>
        /// <param name="match">The match.</param>
        /// <returns></returns>
        public int Matches(string url, IRouteContext context, RouteMatch match)
        {
            if (url.ToLowerInvariant() == urlToMatch.ToLowerInvariant())
            {
                context.Response.Redirect(redirectUrl);

                return(100);
            }

            return(0);
        }
Example #9
0
        public override int Matches(string url, IRouteContext context, RouteMatch match)
        {
            var points = base.Matches(url, context, match);

            if ((points == 0) || (string.Compare(restVerbResolver.Resolve(context.Request), requiredVerb, true) != 0))
            {
                return(0);
            }

            return(points);
        }
Example #10
0
        public async Task InvokeRequest_AmbiguousRequest_ErrorResponse()
        {
            RpcRequest stringRequest = RpcRequest.WithParameterList("AmbiguousMethod", new object[] { JToken.FromObject(1) }, "1");

            IRouteContext     routeContext = this.GetRouteContext <TestRouteClass>();
            DefaultRpcInvoker invoker      = this.GetInvoker();
            RpcResponse       response     = await invoker.InvokeRequestAsync(stringRequest, RpcPath.Default, routeContext);

            Assert.NotNull(response.Error);
            Assert.Equal((int)RpcErrorCode.MethodNotFound, response.Error.Code);
        }
        /// <summary>
        /// Gets an update pagination formatted url
        /// </summary>
        /// <param name="urlInfo">The url info</param>
        /// <param name="updatedOffset">The offset to use</param>
        /// <param name="updatedLimit">The limit to use</param>
        /// <returns></returns>
        public static string GetUpdatedPaginationFormattedUrl(this IRouteContext urlInfo, int updatedOffset, int updatedLimit)
        {
            var parameters = urlInfo.Query.ToDictionary(v => v.Key, e => e.Value, StringComparer.OrdinalIgnoreCase);

            parameters[OffsetParameterName] = updatedOffset.ToString();
            parameters[LimitParameterName]  = updatedLimit.ToString();

            var newUrlInfo = new RouteContext(urlInfo.Scheme, urlInfo.Host, urlInfo.Path, parameters.ToList());

            return(newUrlInfo.GetFormattedUrl());
        }
		/// <summary>
		/// Determines if the specified URL matches the
		/// routing rule.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <param name="context">The context</param>
		/// <param name="match">The match.</param>
		/// <returns></returns>
		public int Matches(string url, IRouteContext context, RouteMatch match)
		{
			if (url.ToLowerInvariant() == urlToMatch.ToLowerInvariant())
			{
				context.Response.Redirect(redirectUrl);

				return 100;
			}

			return 0;
		}
Example #13
0
        public async Task InvokeRequest_StringParam_ParseAsGuidType()
        {
            Guid       randomGuid    = Guid.NewGuid();
            RpcRequest stringRequest = RpcRequest.WithParameterList("GuidTypeMethod", new[] { JToken.FromObject(randomGuid.ToString()) }, "1");

            IRouteContext     routeContext   = this.GetRouteContext <TestRouteClass>();
            DefaultRpcInvoker invoker        = this.GetInvoker();
            RpcResponse       stringResponse = await invoker.InvokeRequestAsync(stringRequest, RpcPath.Default, routeContext);


            Assert.Equal(randomGuid, stringResponse.Result);
        }
Example #14
0
        public async Task InvokeRequest_AsyncMethod_Valid()
        {
            RpcRequest stringRequest = RpcRequest.WithParameterList("AddAsync", new object[] { JToken.FromObject(1), JToken.FromObject(1) }, "1");

            IRouteContext     routeContext = this.GetRouteContext <TestRouteClass>();
            DefaultRpcInvoker invoker      = this.GetInvoker();

            RpcResponse response = await invoker.InvokeRequestAsync(stringRequest, RpcPath.Default, routeContext);

            RpcResponse resultResponse = Assert.IsType <RpcResponse>(response);

            Assert.NotNull(resultResponse.Result);
            Assert.Equal(2, resultResponse.Result);
        }
Example #15
0
        public async Task InvokeRequest_ServiceProvider_Pass()
        {
            RpcRequest stringRequest = RpcRequest.WithNoParameters("Test", "1");

            DefaultRpcInvoker invoker         = this.GetInvoker();
            IServiceProvider  serviceProvider = this.GetServiceProvider();
            IRouteContext     routeContext    = this.GetRouteContext <TestIoCRouteClass>();
            RpcResponse       response        = await invoker.InvokeRequestAsync(stringRequest, RpcPath.Default, routeContext);

            RpcResponse resultResponse = Assert.IsType <RpcResponse>(response);

            Assert.NotNull(resultResponse.Result);
            Assert.Equal(1, resultResponse.Result);
        }
Example #16
0
        public async Task InvokeRequest_Int64RequestParam_ConvertToInt32Param()
        {
            RpcRequest stringRequest = RpcRequest.WithParameterList("IntParameter", new object[] { JToken.FromObject(1L) }, "1");

            IRouteContext     routeContext = this.GetRouteContext <TestRouteClass>();
            DefaultRpcInvoker invoker      = this.GetInvoker();

            RpcResponse response = await invoker.InvokeRequestAsync(stringRequest, RpcPath.Default, routeContext);

            RpcResponse resultResponse = Assert.IsType <RpcResponse>(response);

            Assert.NotNull(resultResponse.Result);
            Assert.Equal(1, resultResponse.Result);
        }
Example #17
0
        public async Task InvokeRequest_AmbiguousRequest_ErrorResponse()
        {
            RpcRequest stringRequest = new RpcRequest("1", "AmbiguousMethod", 1);


            var routeCriteria = new List <RouteCriteria>();

            routeCriteria.Add(new RouteCriteria(typeof(TestRouteClass)));
            RpcRoute          route        = new RpcRoute(routeCriteria);
            IRouteContext     routeContext = this.GetRouteContext();
            DefaultRpcInvoker invoker      = this.GetInvoker();
            RpcResponse       response     = await invoker.InvokeRequestAsync(stringRequest, route, routeContext);

            Assert.NotNull(response.Error);
            Assert.Equal(response.Error.Code, (int)RpcErrorCode.MethodNotFound);
        }
Example #18
0
        public async Task InvokeRequest_StringParam_ParseAsGuidType()
        {
            Guid       randomGuid    = Guid.NewGuid();
            RpcRequest stringRequest = new RpcRequest("1", "GuidTypeMethod", randomGuid.ToString());

            var routeCriteria = new List <RouteCriteria>();

            routeCriteria.Add(new RouteCriteria(typeof(TestRouteClass)));
            RpcRoute route = new RpcRoute(routeCriteria);

            IRouteContext     routeContext   = this.GetRouteContext();
            DefaultRpcInvoker invoker        = this.GetInvoker();
            RpcResponse       stringResponse = await invoker.InvokeRequestAsync(stringRequest, route, routeContext);


            Assert.Equal(stringResponse.Result, randomGuid);
        }
Example #19
0
		public int Matches(string url, IRouteContext context, RouteMatch match)
		{
			var parts = GetParts(url);

			if (parts.Length != routeParts.Length)
				return 0;
			
			for (var i = 0; i < parts.Length; i++)
				if (string.Compare(parts[i], routeParts[i], true) != 0)
					return 0;
			
			match.Parameters.Add("area", area);
			match.Parameters.Add("controller", controller);
			match.Parameters.Add("action", action);

			return 100;
		}
Example #20
0
        public async Task InvokeRequest_ServiceProvider_Pass()
        {
            RpcRequest stringRequest = new RpcRequest("1", "Test");
            var        routeCriteria = new List <RouteCriteria>();

            routeCriteria.Add(new RouteCriteria(typeof(TestIoCRouteClass)));
            RpcRoute route = new RpcRoute(routeCriteria);

            DefaultRpcInvoker invoker         = this.GetInvoker();
            IServiceProvider  serviceProvider = this.GetServiceProvider();
            IRouteContext     routeContext    = this.GetRouteContext();
            RpcResponse       response        = await invoker.InvokeRequestAsync(stringRequest, route, routeContext);

            RpcResponse resultResponse = Assert.IsType <RpcResponse>(response);

            Assert.NotNull(resultResponse.Result);
            Assert.Equal(JTokenType.Integer, resultResponse.Result.Type);
            Assert.Equal(resultResponse.Result.Value <int>(), 1);
        }
Example #21
0
        /// <summary>
        /// Determines if the specified URL matches the
        /// routing rule.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="context">The context</param>
        /// <param name="match">The match.</param>
        /// <returns></returns>
        public virtual int Matches(string url, IRouteContext context, RouteMatch match)
        {
            if (verbs.HasValue)
            {
                var requestVerb = (Verb)Enum.Parse(typeof(Verb), context.Request.HttpMethod, true);
                if ((verbs.Value & requestVerb) == 0)
                {
                    return(0);
                }
            }

            var parts  = GetUrlParts(url);
            var points = 0;
            var index  = 0;

            foreach (var node in nodes)
            {
                var part = index < parts.Length ? parts[index] : null;

                if (!node.Matches(part, match, ref points))
                {
                    points = 0;
                    break;
                }

                index++;
            }

            if (points != 0)
            {
                // Fills parameters set on the route that cannot be fulfilled by the url
                foreach (var pair in defaults)
                {
                    if (!match.Parameters.ContainsKey(pair.Key))
                    {
                        match.Parameters.Add(pair.Key, pair.Value);
                    }
                }
            }

            return(points);
        }
Example #22
0
        private async Task <bool> IsAuthorizedAsync(MethodInfo methodInfo, IRouteContext routeContext)
        {
            IEnumerable <Attribute> customClassAttributes   = methodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes();
            List <IAuthorizeData>   authorizeDataListClass  = customClassAttributes.OfType <IAuthorizeData>().ToList();
            IEnumerable <Attribute> customMethodAttributes  = methodInfo.GetCustomAttributes();
            List <IAuthorizeData>   authorizeDataListMethod = customMethodAttributes.OfType <IAuthorizeData>().ToList();

            if (authorizeDataListClass.Any() || authorizeDataListMethod.Any())
            {
                bool allowAnonymousOnClass  = customClassAttributes.OfType <IAllowAnonymous>().Any();
                bool allowAnonymousOnMethod = customMethodAttributes.OfType <IAllowAnonymous>().Any();
                if (allowAnonymousOnClass || allowAnonymousOnMethod)
                {
                    this.logger?.LogDebug("Skipping authorization. Allow anonymous specified for method.");
                }
                else
                {
                    this.logger?.LogDebug($"Running authorization for method.");
                    AuthorizationResult authResult = await this.CheckAuthorize(authorizeDataListClass, routeContext);

                    if (authResult.Succeeded)
                    {
                        //Have to pass both controller and method authorize
                        authResult = await this.CheckAuthorize(authorizeDataListMethod, routeContext);
                    }
                    if (authResult.Succeeded)
                    {
                        this.logger?.LogDebug($"Authorization was successful for user '{routeContext.User.Identity.Name}'.");
                    }
                    else
                    {
                        this.logger?.LogInformation($"Authorization failed for user '{routeContext.User.Identity.Name}'.");
                        return(false);
                    }
                }
            }
            else
            {
                this.logger?.LogDebug("Skipping authorization. None configured for class or method.");
            }
            return(true);
        }
Example #23
0
        public async Task InvokeRequest_Int64RequestParam_ConvertToInt32Param()
        {
            RpcRequest stringRequest = new RpcRequest("1", "IntParameter", (long)1);


            var routeCriteria = new List <RouteCriteria>();

            routeCriteria.Add(new RouteCriteria(typeof(TestRouteClass)));
            RpcRoute          route        = new RpcRoute(routeCriteria);
            IRouteContext     routeContext = this.GetRouteContext();
            DefaultRpcInvoker invoker      = this.GetInvoker();

            RpcResponse response = await invoker.InvokeRequestAsync(stringRequest, route, routeContext);

            RpcResponse resultResponse = Assert.IsType <RpcResponse>(response);

            Assert.NotNull(resultResponse.Result);
            Assert.Equal(JTokenType.Integer, resultResponse.Result.Type);
            Assert.Equal(resultResponse.Result.Value <int>(), 1);
        }
Example #24
0
        public override int Matches(string url, IRouteContext context, RouteMatch match)
        {
            var path = context.Request.Uri
                .GetComponents(UriComponents.Path, UriFormat.Unescaped);

            if (Normalise(path).Equals(Normalise(context.ApplicationPath)) == false)
            {
                return 0;
            }

            foreach (KeyValuePair<string, string> pair in getDefaults(this))
            {
                if (!match.Parameters.ContainsKey(pair.Key))
                {
                    match.Parameters.Add(pair.Key, pair.Value);
                }
            }

            return 100;
        }
Example #25
0
        public async Task InvokeRequest_AsyncMethod_Valid()
        {
            RpcRequest stringRequest = new RpcRequest("1", "AddAsync", 1, 1);


            var routeCriteria = new List <RouteCriteria>();

            routeCriteria.Add(new RouteCriteria(typeof(TestRouteClass)));
            RpcRoute route = new RpcRoute(routeCriteria);

            IRouteContext     routeContext = this.GetRouteContext();
            DefaultRpcInvoker invoker      = this.GetInvoker();

            RpcResponse response = await invoker.InvokeRequestAsync(stringRequest, route, routeContext);

            RpcResponse resultResponse = Assert.IsType <RpcResponse>(response);

            Assert.NotNull(resultResponse.Result);
            Assert.Equal(resultResponse.Result, 2);
        }
Example #26
0
        public async Task InvokeRequest_OptionalParameter_Valid()
        {
            var routeCriteria = new List <RouteCriteria>();

            routeCriteria.Add(new RouteCriteria(typeof(TestRouteClass)));
            RpcRoute route = new RpcRoute(routeCriteria);

            DefaultRpcInvoker invoker         = this.GetInvoker();
            IServiceProvider  serviceProvider = this.GetServiceProvider();
            IRouteContext     routeContext    = this.GetRouteContext();


            //No params specified
            RpcRequest  stringRequest = new RpcRequest("1", "Optional");
            RpcResponse response      = await invoker.InvokeRequestAsync(stringRequest, route, routeContext);

            RpcResponse resultResponse = Assert.IsType <RpcResponse>(response);

            Assert.Null(resultResponse.Result);
            Assert.False(resultResponse.HasError);

            //Param is null
            stringRequest = new RpcRequest("1", "Optional", parameterList: null);
            response      = await invoker.InvokeRequestAsync(stringRequest, route, routeContext);

            resultResponse = Assert.IsType <RpcResponse>(response);
            Assert.Null(resultResponse.Result);
            Assert.False(resultResponse.HasError);


            //Param is a string
            stringRequest = new RpcRequest("1", "Optional", parameterList: "Test");
            response      = await invoker.InvokeRequestAsync(stringRequest, route, routeContext);

            resultResponse = Assert.IsType <RpcResponse>(response);
            Assert.NotNull(resultResponse.Result);
            Assert.Equal(JTokenType.String, resultResponse.Result.Type);
            Assert.Equal(resultResponse.Result.Value <string>(), "Test");
        }
Example #27
0
        public int Matches(string url, IRouteContext context, RouteMatch match)
        {
            var parts = GetParts(url);

            if (parts.Length != routeParts.Length)
            {
                return(0);
            }

            for (var i = 0; i < parts.Length; i++)
            {
                if (string.Compare(parts[i], routeParts[i], true) != 0)
                {
                    return(0);
                }
            }

            match.Parameters.Add("area", area);
            match.Parameters.Add("controller", controller);
            match.Parameters.Add("action", action);

            return(100);
        }
        public static async Task HandleJsonRpcWebSocketRequest(this WebSocket webSocket, HttpContext context, IRpcRequestHandler rpcRequestHandler, IRpcRouteProvider rpcRouteProvider)
        {
            byte[]        buffer       = new byte[1024 * 4];
            IRouteContext routeContext = DefaultRouteContext.FromHttpContext(context, rpcRouteProvider);

            while (webSocket.State == WebSocketState.Open)
            {
                WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                if (result.MessageType != WebSocketMessageType.Text)
                {
                    continue;
                }
                string requestBody = Encoding.ASCII.GetString(buffer);
                string response    = await rpcRequestHandler.HandleRequestAsync(RpcPath.Parse(context.Request.Path), requestBody, routeContext);

                await webSocket.SendAsync(
                    new ArraySegment <byte>(Encoding.ASCII.GetBytes(response), 0, response.Length),
                    WebSocketMessageType.Text,
                    true,
                    CancellationToken.None
                    );
            }
        }
Example #29
0
        /// <summary>
        /// Call the incoming Rpc request method and gives the appropriate response
        /// </summary>
        /// <param name="request">Rpc request</param>
        /// <param name="route">Rpc route that applies to the current request</param>
        /// <param name="httpContext">The context of the current http request</param>
        /// <param name="jsonSerializerSettings">Json serialization settings that will be used in serialization and deserialization for rpc requests</param>
        /// <returns>An Rpc response for the request</returns>
        public async Task <RpcResponse> InvokeRequestAsync(RpcRequest request, RpcRoute route, IRouteContext routeContext, JsonSerializerSettings jsonSerializerSettings = null)
        {
            try
            {
                if (request == null)
                {
                    throw new ArgumentNullException(nameof(request));
                }
                if (route == null)
                {
                    throw new ArgumentNullException(nameof(route));
                }
            }
            catch (ArgumentNullException ex)             // Dont want to throw any exceptions when doing async requests
            {
                return(this.GetUnknownExceptionReponse(request, ex));
            }

            this.logger?.LogDebug($"Invoking request with id '{request.Id}'");
            RpcResponse rpcResponse;

            try
            {
                if (!string.Equals(request.JsonRpcVersion, JsonRpcContants.JsonRpcVersion))
                {
                    throw new RpcInvalidRequestException($"Request must be jsonrpc version '{JsonRpcContants.JsonRpcVersion}'");
                }

                object[]  parameterList;
                RpcMethod rpcMethod = this.GetMatchingMethod(route, request, out parameterList, routeContext.RequestServices, jsonSerializerSettings);

                bool isAuthorized = await this.IsAuthorizedAsync(rpcMethod, routeContext);

                if (isAuthorized)
                {
                    this.logger?.LogDebug($"Attempting to invoke method '{request.Method}'");
                    object result = await rpcMethod.InvokeAsync(parameterList);

                    this.logger?.LogDebug($"Finished invoking method '{request.Method}'");

                    JsonSerializer jsonSerializer = JsonSerializer.Create(jsonSerializerSettings);
                    if (result is IRpcMethodResult)
                    {
                        this.logger?.LogTrace($"Result is {nameof(IRpcMethodResult)}.");
                        rpcResponse = ((IRpcMethodResult)result).ToRpcResponse(request.Id, obj => JToken.FromObject(obj, jsonSerializer));
                    }
                    else
                    {
                        this.logger?.LogTrace($"Result is plain object.");
                        JToken resultJToken = result != null?JToken.FromObject(result, jsonSerializer) : null;

                        rpcResponse = new RpcResponse(request.Id, resultJToken);
                    }
                }
                else
                {
                    var authError = new RpcError(RpcErrorCode.InvalidRequest, "Unauthorized");
                    rpcResponse = new RpcResponse(request.Id, authError);
                }
            }
            catch (RpcException ex)
            {
                this.logger?.LogException(ex, "An Rpc error occurred. Returning an Rpc error response");
                RpcError error = new RpcError(ex, this.serverConfig.Value.ShowServerExceptions);
                rpcResponse = new RpcResponse(request.Id, error);
            }
            catch (Exception ex)
            {
                rpcResponse = this.GetUnknownExceptionReponse(request, ex);
            }

            if (request.Id != null)
            {
                this.logger?.LogDebug($"Finished request with id '{request.Id}'");
                //Only give a response if there is an id
                return(rpcResponse);
            }
            this.logger?.LogDebug($"Finished request with no id. Not returning a response");
            return(null);
        }
Example #30
0
        /// <summary>
        /// Takes a route/http contexts and attempts to parse, invoke, respond to an Rpc request
        /// </summary>
        /// <param name="context">Route context</param>
        /// <returns>Task for async routing</returns>
        public async Task RouteAsync(RouteContext context)
        {
            try
            {
                RpcRoute route;
                bool     matchesRoute = this.parser.MatchesRpcRoute(this.routeProvider, context.HttpContext.Request.Path, out route);
                if (!matchesRoute)
                {
                    return;
                }
                this.logger?.LogInformation($"Rpc request route '{route.Name}' matched");
                try
                {
                    Stream contentStream = context.HttpContext.Request.Body;

                    string jsonString;
                    if (contentStream == null)
                    {
                        jsonString = null;
                    }
                    else
                    {
                        using (StreamReader streamReader = new StreamReader(contentStream))
                        {
                            jsonString = streamReader.ReadToEnd().Trim();
                        }
                    }
                    bool isBulkRequest;
                    List <RpcRequest> requests = this.parser.ParseRequests(jsonString, out isBulkRequest, this.serverConfig.Value.JsonSerializerSettings);
                    this.logger?.LogInformation($"Processing {requests.Count} Rpc requests");

                    int batchLimit = this.serverConfig.Value.BatchRequestLimit;
                    List <RpcResponse> responses;
                    if (batchLimit > 0 && requests.Count > batchLimit)
                    {
                        string batchLimitError = $"Request count exceeded batch request limit ({batchLimit}).";
                        responses = new List <RpcResponse>
                        {
                            new RpcResponse(null, new RpcError(RpcErrorCode.InvalidRequest, batchLimitError))
                        };
                        this.logger?.LogError(batchLimitError + " Returning error response.");
                    }
                    else
                    {
                        IRouteContext routeContext = DefaultRouteContext.FromHttpContext(context.HttpContext);
                        responses = await this.invoker.InvokeBatchRequestAsync(requests, route, routeContext, this.serverConfig.Value.JsonSerializerSettings);
                    }



                    this.logger?.LogInformation($"Sending '{responses.Count}' Rpc responses");
                    await this.SetResponse(context, responses, isBulkRequest, this.serverConfig.Value.JsonSerializerSettings);

                    context.MarkAsHandled();

                    this.logger?.LogInformation("Rpc request complete");
                }
                catch (RpcException ex)
                {
                    context.MarkAsHandled();
                    this.logger?.LogException(ex, "Error occurred when proccessing Rpc request. Sending Rpc error response");
                    await this.SetErrorResponse(context, ex);
                }
            }
            catch (Exception ex)
            {
                string errorMessage = "Unknown exception occurred when trying to process Rpc request. Marking route unhandled";
                this.logger?.LogException(ex, errorMessage);
                context.MarkAsHandled();
            }
        }
			public int Matches(string url, IRouteContext context, RouteMatch match)
			{
				return inner.Matches(url, context, match);
			}
		/// <summary>
		/// Finds the match.
		/// </summary>
		/// <param name="url">The URL.</param>
		/// <param name="context">The context.</param>
		/// <returns></returns>
		public RouteMatch FindMatch(string url, IRouteContext context)
		{
			// TODO: lock for reading

			int winnerPoints = 0;
			RouteMatch winner = null;
			DecoratedRule winnerule = null;

			foreach(DecoratedRule rule in rules)
			{
				RouteMatch match = new RouteMatch();

				int points = rule.Matches(url, context, match);

				if (points != 0 && points > winnerPoints)
				{
					winnerPoints = points;
					winner = match;
					winnerule = rule;
				}
			}

			if (winner != null && winnerule.SelectionAction != null)
			{
				winnerule.SelectionAction(context, winner);
			}

			return winner;
		}
Example #33
0
 /// <summary>
 ///     Returns a <see cref="RouteContextAssertions" /> object that can be used to assert the current
 ///     <see cref="IRouteContext" />.
 /// </summary>
 public static RouteContextAssertions Should(this IRouteContext actualValue)
 {
     return(new RouteContextAssertions(actualValue));
 }
Example #34
0
        /// <summary>
        /// Call the incoming Rpc requests methods and gives the appropriate respones
        /// </summary>
        /// <param name="requests">List of Rpc requests</param>
        /// <param name="path">Rpc path that applies to the current request</param>
        /// <param name="httpContext">The context of the current http request</param>
        /// <returns>List of Rpc responses for the requests</returns>
        public async Task <List <RpcResponse> > InvokeBatchRequestAsync(List <RpcRequest> requests, RpcPath path, IRouteContext routeContext)
        {
            this.logger?.LogDebug($"Invoking '{requests.Count}' batch requests");
            var invokingTasks = new List <Task <RpcResponse> >();

            foreach (RpcRequest request in requests)
            {
                Task <RpcResponse> invokingTask = Task.Run(async() => await this.InvokeRequestAsync(request, path, routeContext).ConfigureAwait(false));;
                invokingTasks.Add(invokingTask);
            }

            await Task.WhenAll(invokingTasks.ToArray());

            List <RpcResponse> responses = invokingTasks
                                           .Select(t => t.Result)
                                           .Where(r => r != null && ((r.Id != null) && ((RpcId)r.Id).HasValue || r.HasError))
                                           .ToList();

            this.logger?.LogDebug($"Finished '{requests.Count}' batch requests");

            return(responses);
        }
Example #35
0
        private async Task <bool> CheckAuthorize(List <IAuthorizeData> authorizeDataList, IRouteContext routeContext)
        {
            if (!authorizeDataList.Any())
            {
                return(true);
            }
            AuthorizationPolicy policy = await AuthorizationPolicy.CombineAsync(this.policyProvider, authorizeDataList);

            return(await this.authorizationService.AuthorizeAsync(routeContext.User, policy));
        }
Example #36
0
 public QueryMapController(IRouteContext routes)
 {
     _routes = routes;
 }
Example #37
0
        /// <summary>
        /// Call the incoming Rpc requests methods and gives the appropriate respones
        /// </summary>
        /// <param name="requests">List of Rpc requests</param>
        /// <param name="route">Rpc route that applies to the current request</param>
        /// <param name="httpContext">The context of the current http request</param>
        /// <param name="jsonSerializerSettings">Json serialization settings that will be used in serialization and deserialization for rpc requests</param>
        /// <returns>List of Rpc responses for the requests</returns>
        public async Task <List <RpcResponse> > InvokeBatchRequestAsync(List <RpcRequest> requests, RpcRoute route, IRouteContext routeContext, JsonSerializerSettings jsonSerializerSettings = null)
        {
            this.logger?.LogDebug($"Invoking '{requests.Count}' batch requests");
            var invokingTasks = new List <Task <RpcResponse> >();

            foreach (RpcRequest request in requests)
            {
                Task <RpcResponse> invokingTask = Task.Run(async() => await this.InvokeRequestAsync(request, route, routeContext, jsonSerializerSettings));
                if (request.Id != null)
                {
                    //Only wait for non-notification requests
                    invokingTasks.Add(invokingTask);
                }
            }

            await Task.WhenAll(invokingTasks.ToArray());

            List <RpcResponse> responses = invokingTasks
                                           .Select(t => t.Result)
                                           .Where(r => r != null)
                                           .ToList();

            this.logger?.LogDebug($"Finished '{requests.Count}' batch requests");

            return(responses);
        }
			public void Render(System.IO.Stream stream, IRouteContext routeContext)
			{
				throw new NotImplementedException();
			}