如何使用 javascript 获取基本 URL?
例如,当我从 Visual Studio 浏览我的网站时,如果我的 URL 是http://localhost:20201/home/index
,我想得到http://localhost:20201
如果我在 IIS 上托管站点,并且虚拟目录名称为 MyApp 并且 URL 为http://localhost/MyApp/home/index
,我想得到http://localhost/MyApp
我尝试使用location.protocol
+ location.hostname
(and location.host
),当我通过 Visual Studio 浏览我的网站时,它们工作正常,但是当我将其托管在 IIS 上时,我得到http://localhost
,/MyApp 被截断。
您应该避免在 JavaScript 中进行此类检测,而是从 .NET 代码传递值。您总是会面临遇到 url 问题的风险,例如http://server/MyApp/MyApp/action
您无法知道哪个是控制器的名称以及哪个是应用程序的路径。
在 Layout.cshtml 文件(或任何需要的地方)中添加以下代码:
<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()
需要部分,以便始终正确组合 URL(无需手动检查每个部分是否以以下开头或结尾/
象征)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)