public UrlShortenerResponse Request(UrlShortenerRequest request)
        {
            var resp = new UrlShortenerResponse {
                Created = DateTime.Now, Success = false
            };

            try
            {
                var req =
                    (HttpWebRequest)
                    WebRequest.Create(string.Format(request.ApiKey,
                                                    HttpUtility.UrlEncode(request.UrlToShorten.ToString())));
                req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                req.Method = "GET";
                var res    = req.GetResponse();
                var stream = res.GetResponseStream();
                if (stream != null)
                {
                    using (var read = new StreamReader(stream))
                    {
                        resp.Message = read.ReadToEnd();
                    }
                }
                resp.Success  = true;
                resp.ShortUrl = new Uri(resp.Message);
            }
            catch (Exception ex)
            {
                resp.Error = ex.ToString();
            }
            return(resp);
        }
Ejemplo n.º 2
0
        public void TestUrlShortenerBitlyService()
        {
            var request = new UrlShortenerRequest()
            {
                ApiKey       = "INSERTAPIKEYHERE",
                UrlToShorten = new Uri("http://www.google.com")
            };
            var service  = new UrlShortenerService();
            var response = service.Request(request);

            Assert.AreEqual("EXPECTEDURLHERE", response.ShortUrl.ToString());
        }
Ejemplo n.º 3
0
        public ActionResult UrlShortener([FromBody] UrlShortenerRequest request)
        {
            if (!UrlValidator.IsValid(request.Url))
            {
                return(BadRequest("Not a valid URL"));
            }
            var id = GenerateShortUrl();
            var shortUrlDetails = new ShortUrlDetail {
                Id = id, OriginalUrl = request.Url, ShortUrl = $"https://localhost:5001/{id}"
            };

            _DB.Add(shortUrlDetails);

            return(Ok(shortUrlDetails));
        }