1. C#

C# Extension To Get Subdomain from URL

Recently, I come across a simple problem where we have to extract subdomain from different URL. Then I decided to write simple extensions in “C# Subdomain from URL”, which can be used easily across the system.

Sharing the code:

public enum GetSubDomainEnum
{
    ExcludeWWW,
    IncludeWWW
};
public static class Extentions
{
    public static string GetSubDomain(this Uri uri,
        GetSubDomainEnum getSubDomainOption = GetSubDomainEnum.IncludeWWW)
    {
        var subdomain = new StringBuilder();
        for (var i = 0; i < uri.Host.Split(new char[]{'.'}).Length - 2; i++)
        {
            if(getSubDomainOption == GetSubDomainEnum.ExcludeWWW && uri.Host.Split(new char[]{'.'})[i].ToLowerInvariant() == "www") continue;
            subdomain.Append((i < uri.Host.Split(new char[]{'.'}).Length - 3 && 
                              uri.Host.Split(new char[]{'.'})[i+1].ToLowerInvariant() != "www") ?                     
                                   uri.Host.Split(new char[]{'.'})[i] + "." :
                                   uri.Host.Split(new char[]{'.'})[i]);
        }
        return subdomain.ToString();
    }
}

USAGE:

var subDomain = Request.Url.GetSubDomain(GetSubDomainOption.ExcludeWWW);
Comments to: C# Extension To Get Subdomain from URL

Your email address will not be published. Required fields are marked *

Nishant Kumar Verma

Full Stack Developer, Experience in enterprise application development. Providing solution for scalable SaaS application and developing product to automate part of development efforts.

#CleanCodeArchitect #.Net #C# #NodeJS #TypeScript #React #JavaScript #DesignPattern #SOLID #WebAPI #HTML5 #Bootstrap #CSS

#AWS #Docker #Kubernetes #GIT #GitHubAction #ECS #LoadBalancer #S3 #Lambda #Azure #CI/CD Pipeline

#MongoDB #MSSQL #MySQL #JSON