How to get base URL of an MVC application using javascript

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).


var url = window.location.href.split('/');
var baseUrl = url[0] + '//' + url[2];

Try the below code.

function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}



document.write(getBaseURL());

Thanks,

Siva


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):

 <script type="text/javascript">
    var url = '@string.Format("{0}://{1}{2}", Context.Request.Scheme, Context.Request.Host.Value , Url.Content("~/"))';
</script>

From version C# 6 with interpolation:

<script type="text/javascript">
    var url = '@($"{Context.Request.Scheme}://{Context.Request.Host.Value}{Url.Content("~/")}")';
</script>