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

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