如何使用javascript获取基本URL?

例如,当我从VisualStudio浏览我的网站时,如果我的URL是http://localhost:20201/home/index,我想得到http://localhost:20201

如果我把我的网站放在IIS上,如果我的虚拟目录名是MyApp,URL是http://localhost/MyApp/home/index,我想得到http://localhost/MyApp

我try 使用location.protocol+location.hostname(和location.host),当我通过visual studio浏览我的网站时,它们工作正常,但当我在IIS上托管它时,我得到http://localhost,/MyApp被截断.

推荐答案

您应该避免在JavaScript中进行此类检测,而应从.NET代码传递该值.您总是有可能在URL(如http://server/MyApp/MyApp/action)中遇到问题,因为您无法知道哪个是控制器的名称,哪个是应用程序的路径.

在你的布局中.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>

需要new Uri()部分,这样URL才能始终正确组合(无需手动判断每个部分是以/符号开头还是结尾).

Asp.net相关问答推荐

try 在 .net 中使用 MS Graph 添加新的应用程序角色时出现 ODataError

在 Windows Server 2008 IIS7 上的 ASP.NET 中写入事件日志(log)

为什么 Web 架构应该是松耦合的?

如何向 Array.IndexOf 添加不区分大小写的选项

Azure 自定义控制器/API .Net 后端

/应用程序中的服务器错误. ASP.NET

使用会话变量有多安全 - asp.net / c#

ASP.NET 控件无法在 Visual Studio 2008 的代码隐藏中引用

我应该使用用户名还是用户 ID 来引用 ASP.NET 中经过身份验证的用户

Web.config 导致被组策略阻止错误

将复选框的值传递给 asp.net mvc4 中的控制器操作

如何在 Visual Studio 2017 中使用 NPM 并安装包?

如何配置 ASP.NET Core 1.0 以使用本地 IIS 而不是 IIS Express?

免费的 ASP.Net 和/或 CSS 主题

ASP.NET 会话超时测试

什么是实体框架中的复杂类型以及何时使用它?

asp.net 网站上的第一页加载缓慢

MSBuild DeployOnBuild=true 不发布

Twitter Bootstrap 和 ASP.NET GridView

将列表转换为 json 格式 - 快速简便的方法