[英]Get Different Base Url using Javascript in Development and Production Site
I'm using javascript to get base url using this code: 我正在使用javascript通过以下代码获取基本网址:
alert(window.location.protocol + "//" + window.location.host);
It will display http://localhost:[port_number] in development site. 它将在开发站点中显示http:// localhost:[port_number] 。 Then, after deploy to production site, it will display http://dev01
然后,部署到生产站点后,它将显示http:// dev01
It gives me wrong base url, since the home url is http://dev01/WebApplication1 . 由于主URL是http:// dev01 / WebApplication1 ,它给了我错误的基本URL。 I can add the application name in the code, so it will be:
我可以在代码中添加应用程序名称,因此它将是:
alert(window.location.protocol + "//" + window.location.host + "/WebApplication1");
but this method is not practical, because I have to remove "/WebApplication1"
when in development site. 但是此方法不切实际,因为在开发站点中必须删除
"/WebApplication1"
。
Is there any workaround for this case? 这种情况下有什么解决方法吗?
Can you simply add some conditional logic to append the subdirectory in production? 您可以简单地添加一些条件逻辑以在生产环境中追加子目录吗?
var host = window.location.host,
path = host === 'dev01' ? '/WebApplication1' : '',
fullPath = window.location.protocol + '//' + host + path;
alert(fullPath);
You need to do this from server side. 您需要从服务器端执行此操作。
The WebApplication1
will change depends on your IIS virtual directory setting WebApplication1
更改取决于您的IIS虚拟目录设置
To have the code working for both Development & Production environemnt 使代码适用于开发和生产环境
Try the following. 尝试以下方法。
in Layout.cshtml 在Layout.cshtml中
<head>
<script>
var base_url = '@Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)@Request.ApplicationPath'
// navigate around the site, base url should be the same
alert(base_url);
</script>
</head>
Try following code it may work: 尝试下面的代码可能会起作用:
var patharray=window.location.pathname.split("/");
alert(window.location.origin+"/"+patharray[1]);
Here window.location.path will give you full path of your site... 在这里,window.location.path将为您提供网站的完整路径...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.