Example #1
0
        private HttpListener searchListener(Uri uri, out HttpListenerPrefix prefix)
        {
            prefix = null;
            if (uri == null)
            {
                return(null);
            }

            var host      = uri.Host;
            var dns       = Uri.CheckHostName(host) == UriHostNameType.Dns;
            var port      = uri.Port;
            var path      = HttpUtility.UrlDecode(uri.AbsolutePath);
            var pathSlash = path[path.Length - 1] == '/' ? path : path + "/";

            HttpListener bestMatch = null;
            var          bestLen   = -1;

            if (host != null && host.Length > 0)
            {
                foreach (var pref in _prefixes.Keys)
                {
                    var ppath = pref.Path;
                    if (ppath.Length < bestLen)
                    {
                        continue;
                    }

                    if (pref.Port != port)
                    {
                        continue;
                    }

                    if (dns)
                    {
                        var phost = pref.Host;
                        if (Uri.CheckHostName(phost) == UriHostNameType.Dns && phost != host)
                        {
                            continue;
                        }
                    }

                    if (path.StartsWith(ppath) || pathSlash.StartsWith(ppath))
                    {
                        bestLen   = ppath.Length;
                        bestMatch = _prefixes[pref];
                        prefix    = pref;
                    }
                }

                if (bestLen != -1)
                {
                    return(bestMatch);
                }
            }

            var list = _unhandled;

            bestMatch = matchFromList(host, path, list, out prefix);
            if (path != pathSlash && bestMatch == null)
            {
                bestMatch = matchFromList(host, pathSlash, list, out prefix);
            }

            if (bestMatch != null)
            {
                return(bestMatch);
            }

            list      = _all;
            bestMatch = matchFromList(host, path, list, out prefix);
            if (path != pathSlash && bestMatch == null)
            {
                bestMatch = matchFromList(host, pathSlash, list, out prefix);
            }

            if (bestMatch != null)
            {
                return(bestMatch);
            }

            return(null);
        }