How do I get the base URL using javascript?
E.g., When I browse my site from visual studio, and if my URL is http://localhost:20201/home/index
, I would want to get http://localhost:20201
If I host my site on IIS, and if my virtual directory name is MyApp and the URL is http://localhost/MyApp/home/index
, I would want to get http://localhost/MyApp
I tried using location.protocol
+ location.hostname
(and location.host
), they work fine when i browse my site via visual studio, but when I host it on IIS, I get http://localhost
, the /MyApp is truncated off.
To find the base URL of your website, go to the site's front page. What you see in the address bar on your site's front page is the base URL of your website.
As you can see in the above figure, the route is configured using the MapRoute() extension method of RouteCollection , where name is "Default", url pattern is "{controller}/{action}/{id}" and defaults parameter for controller, action method and id parameter.
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.
You should avoid doing such detection in JavaScript and instead pass the value from the .NET code. You will always risk running into problems with urls like http://server/MyApp/MyApp/action
where you cannot know which is the name of a controller and which the path to the application.
In your Layout.cshtml file (or wherever you need it) add the following code:
<script type="text/javascript"> window.applicationBaseUrl = @Html.Raw(HttpUtility.JavaScriptStringEncode(Url.Content("~/"), true)); alert(window.applicationBaseUrl + "asd.html"); // if you need to include host and port in the url, use this: window.applicationBaseUrl = @Html.Raw(HttpUtility.JavaScriptStringEncode( new Uri( new Uri(this.Context.Request.Url.GetLeftPart(UriPartial.Authority)), Url.Content("~/") ).ToString(), true)); alert(window.applicationBaseUrl + "asd.html"); </script>
The new Uri()
part is needed so that the URL is always combined correctly (without manually checking if each part starts or ends with /
symbol).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With