06 October, 2021

How to Make a Custom URL Shortener Using C# and .Net Core 3.1

C# and .Net Core 3.1:  Make a Custom URL Shortener


Since a Random URL needs to be random and the intent is to generate short URLs that do not span more than 7 - 15 characters, the real thing is to make these short URLs random in real life too and not just a string that is used in the URLs


Here is a simple clean approach to develop custom solutions


Prerequisite:  Following are used in the demo.


Add a class file named ShortLink.cs and put this code: here we are creating two extension methods.

public static class ShortLink
{
    public static string GetUrlChunk(this long key)=> 
        WebEncoders.Base64UrlEncode(BitConverter.GetBytes(key));

    public static long GetKeyFromUrl(this string urlChunk)=> 
        BitConverter.ToInt64(WebEncoders.Base64UrlDecode(urlChunk));
}


Here is the Calling Sample code 
using System;
using System.Text;
using Microsoft.AspNetCore.WebUtilities;

namespace UrlShorten
{
    class Program
    {
        static void Main(string[] args)
        {
              
            string value = "SOME MEANING DYNAMIC/STATIC CONTENT";
            // Convert the string into a byte[].
            byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
            long temp = 0;
            foreach (var item in asciiBytes)
                temp += item;
            // key = Tiks + sub of string bytes: that will be always unique
          var key = DateTime.UtcNow.Ticks + temp;
            Console.WriteLine($"Dynamic Key: {key}");
            var generatedUrl = key.GetUrlChunk();
            Console.WriteLine($"Generated URL: {generatedUrl}");
            Console.WriteLine($"Key From URL: {generatedUrl.GetKeyFromUrl()}");
            Console.ReadKey();
        }
    }
}

Here is the final output


No comments:

Post a Comment

Microservices vs Monolithic Architecture

 Microservices vs Monolithic Architecture Here’s a clear side-by-side comparison between Microservices and Monolithic architectures — fro...