如何获得用javascript MVC应用程序的基本URL [英] How to get base URL of an MVC application using javascript

查看:138
本文介绍了如何获得用javascript MVC应用程序的基本URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用javascript得到基本URL?

How do I get the base URL using javascript?

例如,当我浏览我的网站从Visual Studio,如果我的网址是的http://本地主机:20201 /家用/指数,我希望得到的http://本地主机:20201

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

如果我主持我的网站在IIS上,如果我的虚拟目录名称为MyApp的,网址为的http://本地主机/ MyApp的/家庭/指数,我会想获得的http://本地主机/ MyApp的

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

我试着用 location.protocol + location.hostname (和 location.host ),他们的工作很好,当我通过视觉工作室浏览我的网站,但是当我主持它在IIS上,我得到的http://本地主机,在/ 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.

推荐答案

您应该避免做在JavaScript中这种检测,而是通过从.NET code中的价值。你总是会冒险运行到像的HTTP URL的问题://服务器/ MyApp的/ MyApp的/动作在那里你可以不知道这是一个控制器的名称和路径应用程序。

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.

在您Layout.cshtml文件(或任何你需要它)添加以下code:

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>

是必须的新的URI()一部分,这样的URL始终正确组合(不含如果每个部分开始手动检查或 /结束符号)。

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

这篇关于如何获得用javascript MVC应用程序的基本URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆