hosting tips

ASP.NET Tutorial: How to Building a URL Shortener with .NET?

Because they offer brief URLs that are simple to share and remember, URL shorteners have become an essential component of the internet. We’ll look at how to create a URL shortener with the.NET framework in this tutorial. The strong web applications that developers may construct with Microsoft.NET are made possible by its powerful and adaptable foundation. To build a straightforward and effective URL shortener, we’ll make use of the cross-platform, high-performance framework ASP.NET Core.

Required conditions

Make sure you have installed the necessary tools and technologies before we start.

Visual Studio: Visit the official Microsoft website to download and install the most recent version of Visual Studio.
.NET Core SDK: Verify that your computer is running the.NET Core SDK. It is available for download on the official.NET website.

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.

ASP.NET Core 8 Hosting Recommendation

HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.