/// <summary> /// Adds all methods marked with the <see cref="RouteAttribute"/> in the type <paramref name="type"/> to this router's list of routes. /// </summary> /// <param name="type">The type that who's methods should be added as routes to the router.</param> public void AddRoutes(Type type) { foreach (var method in type.GetMethods()) { var attrib = method.GetCustomAttribute <RouteAttribute>(); if (attrib != null) { RouteMetadata meta = new RouteMetadata(type, method, attrib); if (meta.BodyTransformer == null) { meta.BodyTransformer = DefaultBodyTransformer; } _routes.Add(meta); Logger.Default.Info("Router", $"Found route {type.Name}#{method.Name} for {attrib.Pattern}."); } } }
public bool TryMatch(RouteMetadata route, HttpListenerContext context, ParamReplacer paramReplacer) { try { if (context.Request.HttpMethod.Equals(route.HttpMethod, StringComparison.OrdinalIgnoreCase)) { string pattern = paramReplacer.ReplacePattern(route.Pattern); bool isPost = context.Request.HttpMethod.Equals("post", StringComparison.OrdinalIgnoreCase); int argLen = route.MethodParams.Length - (isPost ? 1 : 0); var match = Regex.Match(context.Request.Url.LocalPath, $"^{pattern}$"); if (match.Success && argLen == match.Groups.Count - 1) { Parameters = new object[route.MethodParams.Length]; for (int i = 0; i < argLen; i++) { var param = route.MethodParams[i]; Parameters[i] = Convert.ChangeType(match.Groups[param.Name].Value, param.ParameterType); } if (isPost) { try { Parameters[argLen] = route.BodyTransformer.Transform(route.MethodParams[argLen].ParameterType, context.Request.InputStream); } catch (Exception e) { FatalError = e; } } return(Success = true); } } } catch (Exception) { } return(Success = false); }