[c#] How can I get the baseurl of site?

I want to write a little helper method which returns the base URL of the site. This is what I came up with:

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;
}

Is there any mistake in this, that you can think of? Can anyone improve upon this?

This question is related to c# asp.net uri httprequest

The answer is


string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority)

That's it ;)


I'm using following code from Application_Start

String baseUrl = Path.GetDirectoryName(HttpContext.Current.Request.Url.OriginalString);


Based on what Warlock wrote, I found that the virtual path root is needed if you aren't hosted at the root of your web. (This works for MVC Web API controllers)

String baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) 
+ Configuration.VirtualPathRoot;

I go with

HttpContext.Current.Request.ServerVariables["HTTP_HOST"]

Please use the below code                           

string.Format("{0}://{1}", Request.url.Scheme, Request.url.Host);

To me, @warlock's looks like the best answer here so far, but I've always used this in the past;

string baseUrl = Request.Url.GetComponents(
    UriComponents.SchemeAndServer, UriFormat.UriEscaped)   

Or in a WebAPI controller;

string baseUrl = Url.Request.RequestUri.GetComponents(
    UriComponents.SchemeAndServer, UriFormat.Unescaped)

which is handy so you can choose what escaping format you want. I'm not clear why there are two such different implementations, and as far as I can tell, this method and @warlock's return the exact same result in this case, but it looks like GetLeftPart() would also work for non server Uri's like mailto tags for instance.


The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:

uri.GetComponents(
    UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);

I believe that the answers above doesn't consider when the site is not in the root of the website.

This is a for WebApi controller:

string baseUrl = (Url.Request.RequestUri.GetComponents(
                    UriComponents.SchemeAndServer, UriFormat.Unescaped).TrimEnd('/') 
                 + HttpContext.Current.Request.ApplicationPath).TrimEnd('/') ;

This works for me.

Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + Request.ApplicationPath;
  • Request.Url.OriginalString: return the complete path same as browser showing.
  • Request.Url.PathAndQuery: return the (complete path) - (domain name + PORT).
  • Request.ApplicationPath: return "/" on hosted server and "application name" on local IIS deploy.

So if you want to access your domain name do consider to include the application name in case of:

  1. IIS deployment
  2. If your application deployed on the sub-domain.

====================================

For the dev.x.us/web

it return this strong text


you could possibly add in the port for non port 80/SSL?

something like:

if (HttpContext.Current.Request.ServerVariables["SERVER_PORT"] != null && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "80" && HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString() != "443")
            {
                port = String.Concat(":", HttpContext.Current.Request.ServerVariables["SERVER_PORT"].ToString());
            }

and use that in the final result?


This is a much more fool proof method.

VirtualPathUtility.ToAbsolute("~/");

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 asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

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?

Examples related to httprequest

Http post and get request in angular 6 Postman: How to make multiple requests at the same time Adding header to all request with Retrofit 2 Understanding Chrome network log "Stalled" state Why is this HTTP request not working on AWS Lambda? Simulate a specific CURL in PostMan HTTP Request in Swift with POST method What are all the possible values for HTTP "Content-Type" header? How to get host name with port from a http or https request Why I get 411 Length required error?