The next generation of the Teknik Services. Written in ASP.NET. Fork for blog tags.
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

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