The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ShortenerController.cs 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using Teknik.Areas.Shortener.Models;
  7. using Teknik.Areas.Shortener.ViewModels;
  8. using Teknik.Controllers;
  9. using Teknik.Filters;
  10. using Teknik.Models;
  11. namespace Teknik.Areas.Shortener.Controllers
  12. {
  13. public class ShortenerController : DefaultController
  14. {
  15. private TeknikEntities db = new TeknikEntities();
  16. [TrackPageView]
  17. [AllowAnonymous]
  18. public ActionResult Index()
  19. {
  20. ViewBag.Title = "Url Shortener - " + Config.Title;
  21. ShortenViewModel model = new ShortenViewModel();
  22. return View(model);
  23. }
  24. [AllowAnonymous]
  25. public ActionResult RedirectToUrl(string url)
  26. {
  27. ShortenedUrl shortUrl = db.ShortenedUrls.Where(s => s.ShortUrl == url).FirstOrDefault();
  28. if (shortUrl != null)
  29. {
  30. shortUrl.Views += 1;
  31. db.Entry(shortUrl).State = System.Data.Entity.EntityState.Modified;
  32. db.SaveChanges();
  33. return Redirect(shortUrl.OriginalUrl);
  34. }
  35. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  36. }
  37. [HttpPost]
  38. [AllowAnonymous]
  39. public ActionResult ShortenUrl(string url)
  40. {
  41. if (url.IsValidUrl())
  42. {
  43. ShortenedUrl newUrl = Shortener.ShortenUrl(url, Config.ShortenerConfig.UrlLength);
  44. if (User.Identity.IsAuthenticated)
  45. {
  46. Users.Models.User foundUser = db.Users.Where(u => u.Username == User.Identity.Name).FirstOrDefault();
  47. if (foundUser != null)
  48. {
  49. newUrl.UserId = foundUser.UserId;
  50. }
  51. }
  52. db.ShortenedUrls.Add(newUrl);
  53. db.SaveChanges();
  54. string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Url.Scheme, Config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
  55. if (Config.DevEnvironment)
  56. {
  57. shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
  58. }
  59. return Json(new { result = new { shortUrl = shortUrl, originalUrl = url } });
  60. }
  61. return Json(new { error = "Must be a valid Url" });
  62. }
  63. }
  64. }