Introduction
URL shorteners have become an integral part of the internet, providing concise links that are easy to share and remember. In this article, we'll explore how to build a URL shortener using the .NET framework. .NET, developed by Microsoft, is a versatile and powerful framework that allows developers to create robust web applications. We'll leverage ASP.NET Core, a cross-platform, high-performance framework, to create a simple and efficient URL shortener.
Prerequisites
Before we begin, make sure you have the following tools and technologies installed.
- Visual Studio: Download and install the latest version of Visual Studio from the official Microsoft website.
- .NET Core SDK: Ensure that you have the .NET Core SDK installed on your machine. You can download it from the official .NET website.
Step 1. Create a new ASP.NET Core Web Application
Open Visual Studio and create a new ASP.NET Core Web Application. Choose the "Empty" template to start with a minimal project structure.
Step 2. Set Up the Database
We'll use Entity Framework Core to manage our database for this example. Please create a new class representing our data model and a DbContext class to interact with the database.
public class UrlShortenerContext : DbContext
{
public UrlShortenerContext(DbContextOptions<UrlShortenerContext> options)
: base(options)
{
}
public DbSet<UrlMapping> UrlMappings { get; set; }
}
public class UrlMapping
{
public int Id { get; set; }
public string OriginalUrl { get; set; }
public string ShortenedUrl { get; set; }
}
Step 3. Implement URL Shortening Logic
Create a service to handle the URL shortening and redirection logic. In this service, generate a unique shortcode for each URL and store it in the database.
public class UrlShortenerService
{
private readonly UrlShortenerContext _context;
public UrlShortenerService(UrlShortenerContext context)
{
_context = context;
}
public string ShortenUrl(string originalUrl)
{
var mapping = new UrlMapping
{
OriginalUrl = originalUrl,
ShortenedUrl = GenerateShortCode()
};
_context.UrlMappings.Add(mapping);
_context.SaveChanges();
return mapping.ShortenedUrl;
}
public string GetOriginalUrl(string shortCode)
{
var mapping = _context.UrlMappings.FirstOrDefault(x => x.ShortenedUrl == shortCode);
return mapping?.OriginalUrl;
}
private string GenerateShortCode()
{
// Implement your short code generation logic here
// For simplicity, you can use a library or generate a unique code based on the original URL
// Make sure the short code is unique to avoid collisions
// Example: return some_unique_short_code;
}
}

Robert AtkinsonPosted Jan 7, 2025, 9:21 PM
I am struggling to follow this, do you have source code available?