How can I get the baseurl of site?

How to Get the Base URL of a Website 🌐
So, you want to get the base URL of a website, huh? This is an important task, especially if you're building web applications or just want to know the root of a website. Don't worry, we got you covered! 👍
The Common Mistake 😱
Before I reveal a better solution, let's take a look at the code snippet you provided:
public static string GetSiteUrl()
{
string url = string.Empty;
HttpRequest request = HttpContext.Current.Request;
if (request.IsSecureConnection)
url = "https://";
else
url = "http://";
url += request["HTTP_HOST"] + "/";
return url;
}At first glance, this code might seem okay, but there's a trap waiting to catch you. The problem lies in accessing request["HTTP_HOST"]. This syntax is wrong. 🚫
A More Reliable Solution 💪
To get the base URL of a website, we need to take a different approach. Here's an improved version of the code:
public static string GetSiteUrl()
{
string scheme = HttpContext.Current.Request.Url.Scheme;
string host = HttpContext.Current.Request.Url.Host;
string port = HttpContext.Current.Request.Url.Port.ToString();
string url = $"{scheme}://{host}";
if (!string.IsNullOrEmpty(port) && port != "80" && port != "443")
{
url += $":{port}";
}
return url;
}Here's what we did differently:
We accessed the base URL using
HttpContext.Current.Request.Url.Schemeto get the URL scheme (e.g., "http" or "https").Then, we obtained the host using
HttpContext.Current.Request.Url.Host.In case the website is hosted on a non-standard port, we added the port number to the URL.
Finally, we returned the complete base URL.
Testing Your Implementation 🚀
To verify whether your implementation works as expected, you can use the following code snippet:
string baseUrl = GetSiteUrl();
Console.WriteLine(baseUrl);Be sure to run this code within a web context, such as an HTTP handler or a controller, to get accurate results.
Share Your Improvements! 🌟
Now that you've learned how to get the base URL of a website correctly, it's time to put that knowledge to use! We encourage you to try out the improved code and let us know if it worked for you. We're all ears for any additional tips or tricks you might have!
So go ahead and share your thoughts in the comments below 👇. Happy coding! 💻✨
Take Your Tech Career to the Next Level
Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.



