public IActionResult Create(ShortenedUrlEntry urlEntry) { _dbContext.UrlEntries.Add(urlEntry); _dbContext.SaveChanges(); urlEntry.Key = _urlShorteningService.Encode(urlEntry.Id); Uri uri = new Uri(urlEntry.Url); Uri baseUri = new Uri(uri.GetLeftPart(UriPartial.Authority)); urlEntry.ShortUrl = new Uri(baseUri, urlEntry.Key).AbsoluteUri; _dbContext.SaveChanges(); return(RedirectToAction(nameof(Index))); }
public Task Invoke(HttpContext httpContext) { var dbContext = httpContext.RequestServices.GetService(typeof(UrlShortenerDbContext)) as UrlShortenerDbContext; string currentUrl = httpContext.Request.GetDisplayUrl(); ShortenedUrlEntry urlToRedirect = dbContext.UrlEntries.FirstOrDefault(entry => entry.ShortUrl == currentUrl); if (urlToRedirect != null) { httpContext.Response.Redirect(urlToRedirect.Url); return(Task.CompletedTask); } return(_next.Invoke(httpContext)); }