Exemplo n.º 1
0
            public void Set(CachedUrl value)
            {
                if (Items.ContainsKey(value.ShortUrl))
                {
                    Items[value.ShortUrl] = value;
                }
                else
                {
                    Items.Add(value.ShortUrl, value);
                }

                List <string> removedItems = null;

                foreach (var item in Items)
                {
                    if (item.Value.Expires < DateTime.Now)
                    {
                        if (removedItems == null)
                        {
                            removedItems = new List <string>();
                        }
                        removedItems.Add(item.Key);
                    }
                }
                if (removedItems != null)
                {
                    foreach (string key in removedItems)
                    {
                        Items.Remove(key);
                    }
                }
            }
Exemplo n.º 2
0
        private string ExpandUrl(string shortUrl)
        {
            CachedUrl cachedUrl = cache.Get(shortUrl);
            string    fullUrl;

            if (cachedUrl != null)
            {
                return(cachedUrl.FullUrl);
            }

            var handler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };

            using (var client = new System.Net.Http.HttpClient(handler))
                using (var request = new HttpRequestMessage(HttpMethod.Head, shortUrl))
                {
                    var clientTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
                    clientTask.Wait();
                    HttpResponseMessage response = clientTask.Result;

                    if (response.StatusCode == HttpStatusCode.MethodNotAllowed) //405
                    {
                        clientTask = client.GetAsync(shortUrl, HttpCompletionOption.ResponseHeadersRead);
                        clientTask.Wait();
                    }


                    HttpStatusCode code = response.StatusCode;

                    if ((int)code == 301 || (int)code == 302 || (int)code == 303 || (int)code == 307)
                    {
                        fullUrl = response.Headers.Location.ToString();
                    }
                    else
                    {
                        return(null);
                    }

                    DateTime expires = ((int)code == 301) ? DateTime.MaxValue : DateTime.Now.AddSeconds(cacheDurationTempRedirect);

                    cache.Set(new CachedUrl {
                        ShortUrl = shortUrl, FullUrl = fullUrl, Expires = expires
                    });

                    return(fullUrl);
                }
        }