如何使用javascript获取MVC应用程序的基本URL

Nul*_*nce 28 javascript asp.net iis url asp.net-mvc

如何使用javascript获取基本URL?

例如,当我从visual studio浏览我的网站时,如果我的网址是http://localhost:20201/home/index,我希望得到http://localhost:20201

如果我在IIS上托管我的网站,如果我的虚拟目录名称是MyApp并且URL是http://localhost/MyApp/home/index,我希望得到http://localhost/MyApp

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

Kna*_*ģis 33

您应该避免在JavaScript中进行此类检测,而是从.NET代码中传递值.您将永远冒险遇到网址问题,例如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>
Run Code Online (Sandbox Code Playgroud)

new Uri()需要该部分,以便始终正确组合URL(无需手动检查每个部分是否以/符号开头或结尾).