public IActionResult LinkShortener(string longURL = null) { string shortURL = longURL; ViewData["Title"] = "Link Shortener"; //If string from post was null, then this field isn't displayed if (longURL != null) { //Randomly choose and int... This will actually be the PK value in the DB Random rnd = new Random(); int value = rnd.Next(0, 100); //Algorithm for shortended link string encoding = Shortener.GetShortEncoding(value); int decoding = Shortener.GetLongDecoding(encoding); string urlHost = Request.Host.ToString(); shortURL = urlHost + "/Home/Go/" + encoding; } ViewData["shortURL"] = shortURL; return(View()); }
//Defualt action of home controller is linkshortener rather than index (changed in route config) //Action takes an optional parameter (longURL) - The url to be shortened public ActionResult LinkShortener(string longURL = null) { //Save the short url as the long url (currently) string shortURL = longURL; //Add the current title to the view bag (for display in the tab on a web broswer) ViewBag.Title = "Link Shortener"; //If string from post was null, then this if statement is never entered if (longURL != null) { //Get the DB instance (and if necessary the DB itself) var dbInstance = LinkDatabase.getInstance(); dbInstance.createDB(); //Save the longurl in the db and save the return as primary key string pk = dbInstance.saveLongURL(longURL); //Encode the PK string encoding = Shortener.GetShortEncoding(Int32.Parse(pk)); //Get the host and port parts of our website url string urlHost = HttpContext.Request.Url.Host; int urlPort = HttpContext.Request.Url.Port; //If no port, ignore adding it to the shortened url if (urlPort == 80) { //Short url looks like: <website name>:<port>/Home/Go/<encoded pk> shortURL = urlHost + "/Home/Go/" + encoding; } else { //Short url looks like: <website name>/Home/Go/<encoded pk> shortURL = urlHost + ":" + urlPort.ToString() + "/Home/Go/" + encoding; } } //Return the shortened (or null) short url to the view ViewBag.shortURL = shortURL; //Render the view return(View()); }