Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the baseurl of site?

People also ask

How do I find the exact URL?

Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc. The following example will display the current url of the page on click of the button.

How do I find the base URL in HTML?

The <base> tag specifies the base URL and/or target for all relative URLs in a document. The <base> tag must have either an href or a target attribute present, or both. There can only be one single <base> element in a document, and it must be inside the <head> element.

What's a Baseurl?

Base URL: The consistent part or the root of your website's address. For example, http://www.YourDomain.com. Relative URL: The remaining path given after the base URL.

What is base URL in PHP?

In the example above, the server used is localhost. The $_SERVER['SERVER_NAME] array returns the server hostname under which the current script is executing. We can use the $_SERVER array to find the base URL of the application in PHP. The SERVER_NAME and REQUEST_URI indices are useful for finding the base URL.


Try this:

string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + 
    Request.ApplicationPath.TrimEnd('/') + "/";

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

That's it ;)


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('/') ;

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.


This is a much more fool proof method.

VirtualPathUtility.ToAbsolute("~/");

I go with

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