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

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