I use JavaScript code to call an MVC web API. It works fine when the current path is:
http://localhost/myApp/Administrator
but it fails when current path is:
http://localhost/myApp/Administrator/
I get the error The resource cannot be found
. Below is the code:
$.getJSON("api/UserApi",
function (data) {
...
});
I don't want to use an absolute URL in the code, e.g.:
$.getJSON("http://localhost/myApp/api/UserApi",
function (data) {
...
});
The absolute URL does work fine, but lacks flexibility. Is there a way to do the same thing as below?
$.getJSON("~/api/UserApi",
function (data) {
...
});
ASP.NET supports the replacement of the "~" character with the current application's root path, e.g.:
http://localhost/myApp
However, the "~" character is not supported in JavaScript files. How do I accomplish the same thing?
The JavaScript is in a standalone file that cannot use ASP.NET statements like Url.Content
. Is there a better way to do it?
I've found the following method. Are there any better solutions?:
1) Write the code below in a .cshtml file
<script type="text/javascript">
var currentDomain = '@Url.Content("~")';
</script>
2) Read the currentDomain
variable from the .js file:
$.getJSON(currentDomain + "/api/UserApi",
function (data) {
...
});