In this detailed tutorial, youβll learn how to build a fully functional URL Shortener using ASP.NET Core and Entity Framework Core. This project is perfect for beginners and intermediate developers who want to learn about building REST APIs, database integration, URL mapping, and deploying web apps using .NET Core technologies.
A URL Shortener is a web service that takes a long URL and returns a shorter, more manageable link. When a user visits the shortened URL, they are redirected to the original long URL. Services like Bit.ly and TinyURL are well-known examples.
Hereβs what youβll build in this tutorial:
Open terminal or Visual Studio and create a new ASP.NET Core Web API project:
dotnet new webapi -n UrlShortener
cd UrlShortener
UrlShortener/
βββ Controllers/
β βββ UrlController.cs
βββ Data/
β βββ AppDbContext.cs
βββ Models/
β βββ UrlMapping.cs
βββ Services/
β βββ IUrlService.cs
β βββ UrlService.cs
βββ Program.cs
βββ appsettings.json
This model stores the long URL, short code, and creation timestamp.
using System.ComponentModel.DataAnnotations;
namespace UrlShortener.Models
{
public class UrlMapping
{
[Key]
public int Id { get; set; }
[Required]
public string OriginalUrl { get; set; }
[Required]
public string ShortCode { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}
}
using Microsoft.EntityFrameworkCore;
using UrlShortener.Models;
namespace UrlShortener.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options) {}
public DbSet<UrlMapping> UrlMappings { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using UrlShortener.Data;
using UrlShortener.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite("Data Source=urls.db"));
builder.Services.AddScoped<IUrlService, UrlService>();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
using UrlShortener.Models;
namespace UrlShortener.Services
{
public interface IUrlService
{
Task<UrlMapping> ShortenUrlAsync(string originalUrl);
Task<string> GetOriginalUrlAsync(string shortCode);
}
}
using UrlShortener.Models;
using UrlShortener.Data;
using Microsoft.EntityFrameworkCore;
namespace UrlShortener.Services
{
public class UrlService : IUrlService
{
private readonly AppDbContext _context;
public UrlService(AppDbContext context)
{
_context = context;
}
public async Task<UrlMapping> ShortenUrlAsync(string originalUrl)
{
var existing = await _context.UrlMappings
.FirstOrDefaultAsync(u => u.OriginalUrl == originalUrl);
if (existing != null)
return existing;
string code = Guid.NewGuid().ToString("N").Substring(0, 6);
var mapping = new UrlMapping
{
OriginalUrl = originalUrl,
ShortCode = code
};
_context.UrlMappings.Add(mapping);
await _context.SaveChangesAsync();
return mapping;
}
public async Task<string> GetOriginalUrlAsync(string shortCode)
{
var mapping = await _context.UrlMappings
.FirstOrDefaultAsync(u => u.ShortCode == shortCode);
return mapping?.OriginalUrl;
}
}
}
using Microsoft.AspNetCore.Mvc;
using UrlShortener.Services;
using UrlShortener.Models;
namespace UrlShortener.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UrlController : ControllerBase
{
private readonly IUrlService _urlService;
public UrlController(IUrlService urlService)
{
_urlService = urlService;
}
[HttpPost("shorten")]
public async Task<IActionResult> Shorten([FromBody] UrlRequest request)
{
if (!Uri.IsWellFormedUriString(request.OriginalUrl, UriKind.Absolute))
return BadRequest("Invalid URL");
var result = await _urlService.ShortenUrlAsync(request.OriginalUrl);
var baseUrl = $"{Request.Scheme}://{Request.Host}/";
return Ok(new { ShortUrl = baseUrl + result.ShortCode });
}
[HttpGet("{code}")]
public async Task<IActionResult> RedirectToOriginal(string code)
{
var original = await _urlService.GetOriginalUrlAsync(code);
if (original == null)
return NotFound();
return Redirect(original);
}
}
public class UrlRequest
{
public string OriginalUrl { get; set; }
}
}
dotnet ef migrations add InitialCreate
dotnet ef database update
POST /api/url/shorten
Content-Type: application/json
{
"originalUrl": "https://www.example.com/very/long/link"
}
GET /abc123
This should redirect you to the long URL.
If you want to add a simple UI:
dotnet new razor -n UrlShortener.UI
You can deploy the project to IIS, Azure App Service, or any cloud provider by publishing the build from Visual Studio or using:
dotnet publish -c Release
Building a URL shortener in ASP.NET Core is a great way to explore the fundamentals of web development, routing, APIs, and database operations. This guide covered everything from setting up the project, shortening links, redirecting using short codes, and optionally adding a frontend.
This project can be extended to a production-level microservice or a part of a larger platform.
Copyrights © 2024 letsupdateskills All rights reserved