Example #1
0
        public async Task <IActionResult> Submit(string longUrl)
        {
            string newUrl = tidyUrl(longUrl);

            if (!validateUrlInput(newUrl))
            {
                ViewData["ErrorText"] = "Invalid url " + newUrl;
                return(View("UrlError"));
            }

            //get existing or create
            ShortUrl urlReturn = await _context.ShortUrl
                                 .FirstOrDefaultAsync(m => m.longUrl == newUrl);

            if (urlReturn == null)
            {
                urlReturn = new ShortUrl(newUrl);
                while (!keyUnique(urlReturn.key))
                {
                    urlReturn = new ShortUrl(newUrl);
                }
                if (ModelState.IsValid)
                {
                    _context.Add(urlReturn);
                    await _context.SaveChangesAsync();
                }
                else
                {
                    ViewData["ErrorText"] = "Fatal Error";
                    return(View("UrlError"));
                }
            }
            ViewData["UrlReturn"] = String.Format("{0}://{1}{2}", Request.Scheme, Request.Host, Request.PathBase) + "/" + urlReturn.key;
            return(View());
        }
Example #2
0
        public async Task <IActionResult> Create([Bind("Id,LongUrl,ShortUrl,CreationDate,Counter")] Url url)
        {
            if (ModelState.IsValid)
            {
                var d = from _ in _context.Url where _.LongUrl == url.LongUrl select _;

                if (await d.AnyAsync())
                {
                    return(View("Success", await d.FirstOrDefaultAsync()));
                }

                var hash = ShortUrl.Models.Logic.Hash.Hasher.GetShortHash(url.LongUrl);
                url.ShortUrl = hash;
                url.Counter  = 0;

                _context.Add(url);
                await _context.SaveChangesAsync();

                //return RedirectToAction(nameof(Index));
                return(View("Success", url));
            }
            return(View(url));
        }