以编程方式从Azure网站内部检索站点URL

Azure网站有一个Azure提供的默认“站点URL”,类似于mysite.azurewebsites.net。 是否可以从网站内部(即从ASP.NET应用程序)获取此URL?

Environment和HttpRuntime类中有几个属性包含网站名称(例如“mysite”),因此可以轻松访问。 当不是默认值时,事情变得复杂,但例如访问站点的临时插槽(具有类似mysite-staging.azurewebsites.net的站点URL)。

所以我只是想知道是否有直接获取此站点URL的简单方法。 如果没有,那么使用其中一个提到的类来获取站点名称,然后以某种方式检测站点槽(例如可以通过Azure门户的配置值设置)将是解决方案

编辑(2/4/16):您可以从appSetting / EnvironmentVariable websiteUrl获取URL 。 如果您有一个设置,这也将为您提供自定义主机名。

你可以用很少的方法做到这一点。

1.从HOSTNAME标头

当请求使用.azurewebsites.net该站点时,此选项有效。 然后,您只需查看.azurewebsites.netHOSTNAME标头.azurewebsites.net

 var hostName = Request.Headers["HOSTNAME"].ToString() 

2.来自WEBSITE_SITE_NAME环境变量

这只是为您提供部分,因此您必须附加.azurewebsites.net部分

 var hostName = string.Format("http://{0}.azurewebsites.net", Environment.ExpandEnvironmentVariables("%WEBSITE_SITE_NAME%")); 

3.使用MWAbindingInformation中的bindingInformation

您可以使用此处的代码来读取IIS配置文件applicationHost.config ,然后读取您站点上的bindingInformation属性。 你的function可能看起来有点不同,就像这样

 private static string GetBindings() { // Get the Site name string siteName = System.Web.Hosting.HostingEnvironment.SiteName; // Get the sites section from the AppPool.config Microsoft.Web.Administration.ConfigurationSection sitesSection = Microsoft.Web.Administration.WebConfigurationManager.GetSection(null, null, "system.applicationHost/sites"); foreach (Microsoft.Web.Administration.ConfigurationElement site in sitesSection.GetCollection()) { // Find the right Site if (String.Equals((string) site["name"], siteName, StringComparison.OrdinalIgnoreCase)) { // For each binding see if they are http based and return the port and protocol foreach (Microsoft.Web.Administration.ConfigurationElement binding in site.GetCollection("bindings") ) { var bindingInfo = (string) binding["bindingInformation"]; if (bindingInfo.IndexOf(".azurewebsites.net", StringComparison.InvariantCultureIgnoreCase) > -1) { return bindingInfo.Split(':')[2]; } } } } return null; } 

就个人而言,我会使用2号

此外,您可以使用Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")

这将返回完整的URL( "http://{your-site-name}.azurewebsites.net" ),不需要字符串操作。

要查看环境变量中可用属性的完整列表,只需在SCM PowerShell调试控制台中键入Get-ChildItem Env: