public async Task <UrlDto> AddUrl(UrlCreate url) { // Add the new url to the database if (url == null || url.ActualUrl == null || url.ActualUrl.Trim() == string.Empty) { throw new Exception("Invalid url"); } // Now generate the short url. string shortenedUrl = string.Empty; while (shortenedUrl == string.Empty) { var shortenedValue = Shortener.CreateShortCode(); var existing = _context.Urls.Where(u => u.ShortenedUrl == shortenedValue).FirstOrDefault(); if (existing == null) { shortenedUrl = shortenedValue; } } _context.Urls.Add(new Url { ActualUrl = url.ActualUrl, FriendlyName = url.FriendlyName, ShortenedUrl = shortenedUrl, Created = DateTime.Now }); await _context.SaveChangesAsync(); return(new UrlDto { ActualUrl = url.ActualUrl, ShortenedUrl = shortenedUrl, AccessCount = 0 }); }