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

Pie*_*one 5 c# asp.net azure azure-web-sites

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

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

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

ahm*_*yed 16

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

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

1.从HOSTNAME标题

当请求使用时访问该站点时,此选项有效<SiteName>.azurewebsites.net.然后你可以看一下HOSTNAME标题<SiteName>.azurewebsites.net

var hostName = Request.Headers["HOSTNAME"].ToString()
Run Code Online (Sandbox Code Playgroud)

2.来自WEBSITE_SITE_NAME环境变量

这只是给你的<SiteName>部分,所以你必须附加.azurewebsites.net部分

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

3. bindingInformationapplicationHost.config使用MWA

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 实际上,数字2返回默认的实时站点URL,即使是从暂存插槽也是如此.但是我发现,显然WAWS增加了一个HTTP标头名为DISGUISED_HOST,包括正确的网站网址,甚至在升级插槽(如mysite-staging.azurewebsites.net). (5认同)