Building a URL Shortener with .NET

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.

  1. Visual Studio: Download and install the latest version of Visual Studio from the official Microsoft website.
  2. .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;
    }
}

Step 4. Implement Controllers and Views

Create controllers and views to handle the web interface. Include actions for shortening URLs and redirecting to the original URLs.

public class UrlShortenerController : Controller
{
    private readonly UrlShortenerService _urlShortenerService;

    public UrlShortenerController(UrlShortenerService urlShortenerService)
    {
        _urlShortenerService = urlShortenerService;
    }

    [HttpGet]
    public IActionResult Index()
    {
        // Implement your index action
        // Display the form to enter the URL
        return View();
    }

    [HttpPost]
    public IActionResult ShortenUrl(string originalUrl)
    {
        var shortenedUrl = _urlShortenerService.ShortenUrl(originalUrl);

        // Return the shortened URL to the user
        return View("ShortenedUrl", shortenedUrl);
    }

    [HttpGet("/{shortCode}")]
    public IActionResult RedirectUrl(string shortCode)
    {
        var originalUrl = _urlShortenerService.GetOriginalUrl(shortCode);

        if (originalUrl != null)
        {
            // Redirect to the original URL
            return Redirect(originalUrl);
        }

        // Handle not found scenario
        return NotFound();
    }
}

Step 5. Configure Routing and Dependency Injection

Configure routing in the Startup.cs file to ensure that URLs are mapped correctly to the controller actions. Also, register the UrlShortenerService and UrlShortenerContext with the dependency injection container.

public void ConfigureServices(IServiceCollection services)
{
    // Other configurations...

    services.AddDbContext<UrlShortenerContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddScoped<UrlShortenerService>();

    services.AddControllersWithViews();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Other configurations...

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=UrlShortener}/{action=Index}/{id?}");
    });
}

Step 6. Database Configuration

Configure your database connection in the appsettings.json file.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=UrlShortenerDb;Trusted_Connection=True;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "System": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Step 7. Run the Application

Finally, run your application and test the URL-shortening functionality. Open a web browser and navigate to http://localhost:port to access your URL shortener application.

Conclusion

Building a URL shortener with .NET using ASP.NET Core is a straightforward process. In this guide, we've covered the essential steps to create a simple URL shortener with the .NET framework. You can further enhance and customize the application based on your specific requirements, such as adding user authentication, analytics, and more. Explore the rich ecosystem of .NET to make your URL shortener even more robust and feature-rich.


Recommended Free Ebook
Similar Articles