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.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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.Areas.Users.Utility;
  9. using Teknik.Attributes;
  10. using Teknik.Controllers;
  11. using Teknik.Filters;
  12. using Teknik.Models;
  13. using Teknik.Utilities;
  14. namespace Teknik.Areas.Shortener.Controllers
  15. {
  16. [TeknikAuthorize]
  17. public class ShortenerController : DefaultController
  18. {
  19. [TrackPageView]
  20. [AllowAnonymous]
  21. public ActionResult Index()
  22. {
  23. ViewBag.Title = "Url Shortener - " + Config.Title;
  24. ShortenViewModel model = new ShortenViewModel();
  25. return View(model);
  26. }
  27. [TrackLink]
  28. [AllowAnonymous]
  29. public ActionResult RedirectToUrl(string url)
  30. {
  31. using (TeknikEntities db = new TeknikEntities())
  32. {
  33. ShortenedUrl shortUrl = db.ShortenedUrls.Where(s => s.ShortUrl == url).FirstOrDefault();
  34. if (shortUrl != null)
  35. {
  36. shortUrl.Views += 1;
  37. db.Entry(shortUrl).State = System.Data.Entity.EntityState.Modified;
  38. db.SaveChanges();
  39. return Redirect(shortUrl.OriginalUrl);
  40. }
  41. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  42. }
  43. }
  44. [HttpPost]
  45. [AllowAnonymous]
  46. public ActionResult ShortenUrl(string url)
  47. {
  48. if (url.IsValidUrl())
  49. {
  50. using (TeknikEntities db = new TeknikEntities())
  51. {
  52. ShortenedUrl newUrl = Shortener.ShortenUrl(db, url, Config.ShortenerConfig.UrlLength);
  53. if (User.Identity.IsAuthenticated)
  54. {
  55. Users.Models.User foundUser = UserHelper.GetUser(db, User.Identity.Name);
  56. if (foundUser != null)
  57. {
  58. newUrl.UserId = foundUser.UserId;
  59. }
  60. }
  61. db.ShortenedUrls.Add(newUrl);
  62. db.SaveChanges();
  63. string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Url.Scheme, Config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
  64. if (Config.DevEnvironment)
  65. {
  66. shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
  67. }
  68. return Json(new { result = new { shortUrl = shortUrl, originalUrl = url } });
  69. }
  70. }
  71. return Json(new { error = "Must be a valid Url" });
  72. }
  73. [AllowAnonymous]
  74. public ActionResult Verify()
  75. {
  76. ViewBag.Title = "Url Shortener Verification - " + Config.Title;
  77. return View();
  78. }
  79. }
  80. }