/// <summary> /// Find all RESTRoute decorated methods of a resource and add them as routes. /// The cache owns the resource now. Be sure to call SortRoutes when you are finished /// Add()ing them. /// </summary> /// Note: This method does not set RESTResource.Server /// internal void Add( RESTResource resource ) { // Create a route cache Entry for each valid RESTRoute attribute found foreach (MethodInfo mi in resource.GetType().GetMethods()) { if (!mi.IsStatic && mi.GetCustomAttributes(true).Any(attr => attr is RESTRoute)) { foreach (var attr in mi.GetCustomAttributes(true)) { RESTRoute routeAttr = (RESTRoute)attr; var regex = new Regex(routeAttr.PathInfo, RegexOptions.IgnoreCase | RegexOptions.Compiled); var httpMethod = routeAttr.Method.ToString(); int priority = routeAttr.Priority; _routes.Add( new Entry( resource, mi, regex, httpMethod, priority ) ); } } } }
/// <summary> /// Manually register a rest resource. The resource will be adopted by this class. /// </summary> /// <example> /// server = new RESTServer( Config { AutoLoadRestResource = false; } ); /// server.AddResource( new MyRestResource() ); /// server.Start(); /// </example> public void AddResource( RESTResource resource ) { _routeCache.Add( resource ); }
internal Entry(RESTResource resource, MethodInfo methodInfo, Regex regex, string httpMethod, int priority) { this.RESTResource = resource; this.MethodInfo = methodInfo; this.Regex = regex; this.HttpMethod = httpMethod; this.Priority = priority; }
// // todo: I don't like multiple out parameters, but I don't like special "result" // data structures either. Hmm. // internal bool FindRoute(HttpListenerContext context, out RESTResource resource, out MethodInfo method, out Match match) { var httpMethod = context.Request.HttpMethod.ToUpper(); string url = HttpUtility.UrlDecode( context.Request.Url.AbsolutePath ); foreach (Entry route in _routes) { if (route.Match(url, httpMethod, out match)) { method = route.MethodInfo; resource = route.RESTResource; return true; } } match = null; // out parameters must be set resource = null; method = null; return false; }