Exemplo n.º 1
0
        public IActionResult ShortenUrl(string url)
        {
            if (url.IsValidUrl())
            {
                ShortenedUrl newUrl = ShortenerHelper.ShortenUrl(_dbContext, url, _config.ShortenerConfig.UrlLength);

                if (User.Identity.IsAuthenticated)
                {
                    Users.Models.User foundUser = UserHelper.GetUser(_dbContext, User.Identity.Name);
                    if (foundUser != null)
                    {
                        newUrl.UserId = foundUser.UserId;
                    }
                }

                _dbContext.ShortenedUrls.Add(newUrl);
                _dbContext.SaveChanges();

                string shortUrl = string.Format("{0}://{1}/{2}", Request.Scheme, _config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
                if (_config.DevEnvironment)
                {
                    shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
                }

                return(Json(new { result = new { shortUrl = shortUrl, originalUrl = url } }));
            }
            return(Json(new { error = "Must be a valid Url" }));
        }
Exemplo n.º 2
0
        public IActionResult Shorten(ShortenAPIv1Model model)
        {
            try
            {
                if (model.url.IsValidUrl())
                {
                    ShortenedUrl newUrl = ShortenerHelper.ShortenUrl(_dbContext, model.url, _config.ShortenerConfig.UrlLength);

                    // Associate this with the user if they are logged in
                    if (User.Identity.IsAuthenticated)
                    {
                        User foundUser = UserHelper.GetUser(_dbContext, User.Identity.Name);
                        if (foundUser != null)
                        {
                            newUrl.UserId = foundUser.UserId;
                        }
                    }

                    _dbContext.ShortenedUrls.Add(newUrl);
                    _dbContext.SaveChanges();

                    string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Scheme, _config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
                    if (_config.DevEnvironment)
                    {
                        shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
                    }

                    return(Json(new
                    {
                        result = new
                        {
                            shortUrl = shortUrl,
                            originalUrl = model.url
                        }
                    }));
                }
                return(Json(new { error = new { message = "Must be a valid Url" } }));
            }
            catch (Exception ex)
            {
                return(Json(new { error = new { message = "Exception: " + ex.Message } }));
            }
        }