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.
I think a clean solution will be like
Putting the base URL in the
_layout
Html like soContext.Request.Url.GetLeftPart(UriPartial.Authority) will give you in
local http://localhost:20201 from IIS will give you http://localhost
Url.Content("~/") in the local will be empty but in IIS will give you the app name, in your case MyApp
Then from the Js:
Than you can Use it Like:
https://msdn.microsoft.com/en-us/library/system.uri.getleftpart(v=vs.110).aspx http://api.jquery.com/data/
Define it in layout file and append base_url. This worked for me.
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:
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).Try the below code.
Thanks,
Siva
I don't think that this is possible as the JavaScript (the Client) doesn't know anything about your deployment (MyApp) and treats it as part of the pathinfo (just like /home/index). As a workaround you could try to interpret the pathinfo (location.pathname) according to the domain or port.
But you could set a JavaScript variable in a global scope (or what ever suits you) containing the path (the path is generated by the server and placed into the variable).
This could look something like that in your html-Head:
If you are using .NET Core, you can get url setting a JavaScript variable in a global scope (For example in Layout.cshtml File, this file is in the folder Views/Shared):
From version C# 6 with interpolation: