更新时间:2023-10-17 23:35:10
您应该避免做在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).