Created
November 28, 2019 00:05
-
-
Save bolorundurowb/080c36c0f465db064a072478f82b92fd to your computer and use it in GitHub Desktop.
Creating a URL Shortener with C# ASP.NET Core and MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.Extensions.Logging; | |
using MongoDB.Driver; | |
using MongoDB.Driver.Linq; | |
using shortid; | |
using url_shortener.Models; | |
namespace url_shortener.Controllers | |
{ | |
public class HomeController : Controller | |
{ | |
private readonly ILogger<HomeController> _logger; | |
private readonly IMongoDatabase _mongoDatabase; | |
private const string ServiceUrl = "http://localhost:5000"; | |
public HomeController(ILogger<HomeController> logger) | |
{ | |
_logger = logger; | |
var connectionString = "mongodb://localhost:27017/"; | |
var mongoClient = new MongoClient(connectionString); | |
_mongoDatabase = mongoClient.GetDatabase("url-shortener"); | |
} | |
public IActionResult Index() | |
{ | |
return View(); | |
} | |
[HttpGet] | |
public async Task<IActionResult> Index(string u) | |
{ | |
// get shortened url collection | |
var shortenedUrlCollection = _mongoDatabase.GetCollection<ShortenedUrl>("shortened-urls"); | |
// first check if we have the short code | |
var shortenedUrl = await shortenedUrlCollection | |
.AsQueryable() | |
.FirstOrDefaultAsync(x => x.ShortCode == u); | |
// if the short code does not exist, send back to home page | |
if (shortenedUrl == null) | |
{ | |
return View(); | |
} | |
return Redirect(shortenedUrl.OriginalUrl); | |
} | |
[HttpPost] | |
public async Task<IActionResult> ShortenUrl(string longUrl) | |
{ | |
// get shortened url collection | |
var shortenedUrlCollection = _mongoDatabase.GetCollection<ShortenedUrl>("shortened-urls"); | |
// first check if we have the url stored | |
var shortenedUrl = await shortenedUrlCollection | |
.AsQueryable() | |
.FirstOrDefaultAsync(x => x.OriginalUrl == longUrl); | |
// if the long url has not been shortened | |
if (shortenedUrl == null) | |
{ | |
var shortCode = ShortId.Generate(length: 8); | |
shortenedUrl = new ShortenedUrl | |
{ | |
CreatedAt = DateTime.UtcNow, | |
OriginalUrl = longUrl, | |
ShortCode = shortCode, | |
ShortUrl = $"{ServiceUrl}?u={shortCode}" | |
}; | |
// add to database | |
await shortenedUrlCollection.InsertOneAsync(shortenedUrl); | |
} | |
return View(shortenedUrl); | |
} | |
public IActionResult Privacy() | |
{ | |
return View(); | |
} | |
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] | |
public IActionResult Error() | |
{ | |
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier}); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@{ | |
ViewData["Title"] = "Home Page"; | |
} | |
<div class="text-center"> | |
<h1 class="display-4">Welcome</h1> | |
<p>A url shortener built with ASP.NET Core and Mongo DB</p> | |
</div> | |
<div style="width: 100%; margin-top: 60px;"> | |
<div style="width: 65%; margin-left: auto; margin-right: auto;"> | |
<form id="form" style="text-align: center;" asp-action="ShortenUrl" method="post"> | |
<input | |
type="text" | |
placeholder="Enter Url ..." | |
style="width: 100%; border-radius: 5px; height: 45px;" | |
name="longUrl"/> | |
<button | |
style="background-color: darkgreen; color: white; padding: 10px; margin-top: 25px; border-radius: 8px;" | |
type="submit"> | |
Shorten Url | |
</button> | |
</form> | |
</div> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using MongoDB.Bson; | |
using MongoDB.Bson.Serialization.Attributes; | |
namespace url_shortener.Models | |
{ | |
public class ShortenedUrl | |
{ | |
[BsonId] | |
public ObjectId Id { get; set; } | |
public string OriginalUrl { get; set; } | |
public string ShortCode { get; set; } | |
public string ShortUrl { get; set; } | |
public DateTime CreatedAt { get; set; } | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@model ShortenedUrl; | |
@{ | |
ViewData["Title"] = "Shortened Url"; | |
} | |
<div style="width: 100%; padding: 30px;"> | |
<div> | |
<div>Short Code: @Model.ShortCode</div> | |
<div>Short Url: @Model.ShortUrl</div> | |
<div>Long Url: @Model.OriginalUrl</div> | |
</div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment