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.

ShortenAPIv1Controller.cs 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Authorization;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.Extensions.Logging;
  8. using Teknik.Areas.API.Controllers;
  9. using Teknik.Areas.API.V1.Models;
  10. using Teknik.Areas.Shortener;
  11. using Teknik.Areas.Shortener.Models;
  12. using Teknik.Areas.Users.Models;
  13. using Teknik.Areas.Users.Utility;
  14. using Teknik.Configuration;
  15. using Teknik.Data;
  16. using Teknik.Logging;
  17. using Teknik.Utilities;
  18. namespace Teknik.Areas.API.V1.Controllers
  19. {
  20. [Authorize(Policy = "WriteAPI")]
  21. public class ShortenAPIv1Controller : APIv1Controller
  22. {
  23. public ShortenAPIv1Controller(ILogger<Logger> logger, Config config, TeknikEntities dbContext) : base(logger, config, dbContext) { }
  24. [HttpPost]
  25. [AllowAnonymous]
  26. public IActionResult Shorten(ShortenAPIv1Model model)
  27. {
  28. try
  29. {
  30. if (model.url.IsValidUrl())
  31. {
  32. ShortenedUrl newUrl = ShortenerHelper.ShortenUrl(_dbContext, model.url, _config.ShortenerConfig.UrlLength);
  33. // Associate this with the user if they are logged in
  34. if (User.Identity.IsAuthenticated)
  35. {
  36. User foundUser = UserHelper.GetUser(_dbContext, User.Identity.Name);
  37. if (foundUser != null)
  38. {
  39. newUrl.UserId = foundUser.UserId;
  40. }
  41. }
  42. _dbContext.ShortenedUrls.Add(newUrl);
  43. _dbContext.SaveChanges();
  44. string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Scheme, _config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
  45. if (_config.DevEnvironment)
  46. {
  47. shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
  48. }
  49. return Json(new
  50. {
  51. result = new
  52. {
  53. shortUrl = shortUrl,
  54. originalUrl = model.url
  55. }
  56. });
  57. }
  58. return Json(new { error = new { message = "Must be a valid Url" } });
  59. }
  60. catch (Exception ex)
  61. {
  62. return Json(new { error = new { message = "Exception: " + ex.Message } });
  63. }
  64. }
  65. }
  66. }