.NET - Build a URL Shortener with ASP.NET Core

Build a URL Shortener with ASP.NET Core - Complete Guide

Build a URL Shortener with ASP.NET Core

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.

What is a URL Shortener?

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.

Project Overview

Here’s what you’ll build in this tutorial:

  • API endpoint to shorten long URLs
  • Redirection endpoint that maps short URLs to original URLs
  • Entity Framework Core integration for URL storage
  • Base62 or random code generation
  • Minimal frontend using Razor Pages or HTML

Technologies Used

  • ASP.NET Core 7.0 or later
  • Entity Framework Core
  • SQLite or SQL Server (lightweight database)
  • C# .NET
  • Visual Studio or VS Code

Step 1: Create ASP.NET Core Web API Project

Open terminal or Visual Studio and create a new ASP.NET Core Web API project:

dotnet new webapi -n UrlShortener
cd UrlShortener

Project Structure

UrlShortener/
β”œβ”€β”€ Controllers/
β”‚   └── UrlController.cs
β”œβ”€β”€ Data/
β”‚   └── AppDbContext.cs
β”œβ”€β”€ Models/
β”‚   └── UrlMapping.cs
β”œβ”€β”€ Services/
β”‚   └── IUrlService.cs
β”‚   └── UrlService.cs
β”œβ”€β”€ Program.cs
└── appsettings.json

Step 2: Create the UrlMapping Model

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;
    }
}

Step 3: Set Up Database Context

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; }
    }
}

Step 4: Configure Entity Framework in Program.cs

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();

Step 5: Implement URL Service

IUrlService.cs

using UrlShortener.Models;

namespace UrlShortener.Services
{
    public interface IUrlService
    {
        Task<UrlMapping> ShortenUrlAsync(string originalUrl);
        Task<string> GetOriginalUrlAsync(string shortCode);
    }
}

UrlService.cs

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;
        }
    }
}

Step 6: Create the UrlController

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; }
    }
}

Step 7: Run Migrations

dotnet ef migrations add InitialCreate
dotnet ef database update

Step 8: Testing the API

Shorten URL

POST /api/url/shorten
Content-Type: application/json

{
    "originalUrl": "https://www.example.com/very/long/link"
}

Redirect to Original

GET /abc123

This should redirect you to the long URL.

Optional: Add Razor Page for Simple UI

If you want to add a simple UI:

dotnet new razor -n UrlShortener.UI

Step 9: Deploy to IIS or Azure

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

Advanced Features (Optional)

  • Track analytics (number of clicks, location)
  • Authentication for shortening links
  • Custom short codes
  • Expiration dates


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.

Beginner 5 Hours
Build a URL Shortener with ASP.NET Core - Complete Guide

Build a URL Shortener with ASP.NET Core

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.

What is a URL Shortener?

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.

Project Overview

Here’s what you’ll build in this tutorial:

  • API endpoint to shorten long URLs
  • Redirection endpoint that maps short URLs to original URLs
  • Entity Framework Core integration for URL storage
  • Base62 or random code generation
  • Minimal frontend using Razor Pages or HTML

Technologies Used

  • ASP.NET Core 7.0 or later
  • Entity Framework Core
  • SQLite or SQL Server (lightweight database)
  • C# .NET
  • Visual Studio or VS Code

Step 1: Create ASP.NET Core Web API Project

Open terminal or Visual Studio and create a new ASP.NET Core Web API project:

dotnet new webapi -n UrlShortener cd UrlShortener

Project Structure

UrlShortener/ ├── Controllers/ │ └── UrlController.cs ├── Data/ │ └── AppDbContext.cs ├── Models/ │ └── UrlMapping.cs ├── Services/ │ └── IUrlService.cs │ └── UrlService.cs ├── Program.cs └── appsettings.json

Step 2: Create the UrlMapping Model

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; } }

Step 3: Set Up Database Context

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; } } }

Step 4: Configure Entity Framework in Program.cs

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();

Step 5: Implement URL Service

IUrlService.cs

using UrlShortener.Models; namespace UrlShortener.Services { public interface IUrlService { Task<UrlMapping> ShortenUrlAsync(string originalUrl); Task<string> GetOriginalUrlAsync(string shortCode); } }

UrlService.cs

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; } } }

Step 6: Create the UrlController

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; } } }

Step 7: Run Migrations

dotnet ef migrations add InitialCreate dotnet ef database update

Step 8: Testing the API

Shorten URL

POST /api/url/shorten Content-Type: application/json { "originalUrl": "https://www.example.com/very/long/link" }

Redirect to Original

GET /abc123

This should redirect you to the long URL.

Optional: Add Razor Page for Simple UI

If you want to add a simple UI:

dotnet new razor -n UrlShortener.UI

Step 9: Deploy to IIS or Azure

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

Advanced Features (Optional)

  • Track analytics (number of clicks, location)
  • Authentication for shortening links
  • Custom short codes
  • Expiration dates


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.

Related Tutorials

Frequently Asked Questions for General

line

Copyrights © 2024 letsupdateskills All rights reserved