public static async Task ExecuteRequest(HttpListenerRequest request, HttpListenerResponse response)
        {
            RouteInfo routeInfo = Reflection.RouteRegistered
                                  .FirstOrDefault(x => Regex.IsMatch(request.Url.AbsolutePath,
                                                                     Regex.Replace(x.AbsoluteUrl, @"(?<=\$).+", string.Empty)) &&
                                                  x.HttpVers.ToString() == request.HttpMethod);

            try
            {
                if (routeInfo != null &&
                    request.HttpMethod == routeInfo.HttpVers.ToString())
                {
                    ExecuteRoute(routeInfo, request, response);
                }
            }
            catch (Exception ex)
            {
                OutputResponse(ex, request, response);
            }
            return;
        }
Beispiel #2
0
        public static void BuildRouter(string baseRoute, MethodInfo method, ref RouteInfo routeInfo, RouteAttribute attribute = null)
        {
            routeInfo = new RouteInfo();
            string restPart = attribute != null && !string.IsNullOrWhiteSpace(attribute.Route)
                ? attribute.Route
                : method.Name;

            string absoluteUrl = Regex.Replace($"/{baseRoute}/{restPart}", "(/)+", "/");

            string[] segmentUrl = absoluteUrl.Split('/', StringSplitOptions.RemoveEmptyEntries);

            MatchCollection matches = Regex.Matches(absoluteUrl,
                                                    @"(?<={)(?<name>[a-zA-Z0-9_-]+)(?=})",
                                                    RegexOptions.IgnoreCase | RegexOptions.Multiline);

            if (matches.Count > 0)
            {
                absoluteUrl = $"{Regex.Replace(absoluteUrl, @"{(?<name>[a-zA-Z0-9_-]+)}", @"([a-zA-Z0-9_-]+)")}";
                //var data = Regex.Matches("/api/param1/param2", absoluteUrl);

                var param = method.GetParameters()
                            .Select(x => x.Name)
                            .ToArray();
                routeInfo.ParamSegments = segmentUrl.Select(x => Array.FindIndex(param, p => $"{{{p}}}" == x)).ToArray();
            }

            routeInfo.AbsoluteUrl = $"^{absoluteUrl}$";
            routeInfo.Action      = method.DeclaringType;
            routeInfo.Method      = method;

            ParameterInfo[] parameters = method.GetParameters();

            routeInfo.ParamNames     = parameters.Select(x => x.Name.ToLower()).ToArray();
            routeInfo.BodyParametter = parameters.FirstOrDefault(x => x.ParameterType != typeof(string))?.ParameterType.FullName;

            routeInfo.HttpVers = attribute != null
                ? attribute.HttpVerb
                : HttpMethod.GET;
        }