[c#] Get host domain from URL?

how to get host domain from a string URL?

GetDomain has 1 input "URL", 1 Output "Domain"

Example1

INPUT: http://support.domain.com/default.aspx?id=12345
OUTPUT: support.domain.com

Example2

INPUT: http://www.domain.com/default.aspx?id=12345
OUTPUT: www.domain.com

Example3

INPUT: http://localhost/default.aspx?id=12345
OUTPUT: localhost

This question is related to c# string url httpwebrequest uri

The answer is


You should construct your string as URI object and Authority property returns what you need.


Try like this;

Uri.GetLeftPart( UriPartial.Authority )

Defines the parts of a URI for the Uri.GetLeftPart method.


http://www.contoso.com/index.htm?date=today --> http://www.contoso.com

http://www.contoso.com/index.htm#main --> http://www.contoso.com

nntp://news.contoso.com/[email protected] --> nntp://news.contoso.com

file://server/filename.ext --> file://server

Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search");
Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Authority));

Demo


 var url = Regex.Match(url, @"(http:|https:)\/\/(.*?)\/");

INPUT = "https://stackoverflow.com/questions/";

OUTPUT = "https://stackoverflow.com/";


Try this

Console.WriteLine(GetDomain.GetDomainFromUrl("http://support.domain.com/default.aspx?id=12345"));

It will output support.domain.com

Or try

Uri.GetLeftPart( UriPartial.Authority )

The best way, and the right way to do it is using Uri.Authority field

Load and use Uri like so :

Uri NewUri;

if (Uri.TryCreate([string with your Url], UriKind.Absolute, out NewUri))
{
     Console.Writeline(NewUri.Authority);
}

Input : http://support.domain.com/default.aspx?id=12345
Output : support.domain.com

Input : http://www.domain.com/default.aspx?id=12345
output : www.domain.com

Input : http://localhost/default.aspx?id=12345
Output : localhost

If you want to manipulate Url, using Uri object is the good way to do it. https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx


WWW is an alias, so you don't need it if you want a domain. Here is my litllte function to get the real domain from a string

private string GetDomain(string url)
    {
        string[] split = url.Split('.');
        if (split.Length > 2)
            return split[split.Length - 2] + "." + split[split.Length - 1];
        else
            return url;

    }

try following statement

 Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
 string pathQuery = myuri.PathAndQuery;
 string hostName = myuri.ToString().Replace(pathQuery , "");

Example1

 Input : http://localhost:4366/Default.aspx?id=notlogin
 Ouput : http://localhost:4366

Example2

 Input : http://support.domain.com/default.aspx?id=12345
 Output: support.domain.com

Use Uri class and use Host property

Uri url = new Uri(@"http://support.domain.com/default.aspx?id=12345");
Console.WriteLine(url.Host);

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?

Examples related to httpwebrequest

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send How to properly make a http web GET request Send JSON via POST in C# and Receive the JSON returned? How to create JSON post to api using C# Use C# HttpWebRequest to send json to web service Post form data using HttpWebRequest HttpWebRequest-The remote server returned an error: (400) Bad Request Get host domain from URL? How to ignore the certificate check when ssl Receiving JSON data back from HTTP request

Examples related to uri

Get Path from another app (WhatsApp) What is the difference between resource and endpoint? Convert a file path to Uri in Android How do I delete files programmatically on Android? java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder How to get id from URL in codeigniter? Get real path from URI, Android KitKat new storage access framework Use URI builder in Android or create URL with variables Converting of Uri to String How are parameters sent in an HTTP POST request?