Programmatically retrieve a website URL from an Azure website

Azure sites have a default "site URL" provided by Azure, something like mysite.azurewebsites.net. Is it possible to get this URL inside the website itself (i.e. from an ASP.NET application)?

The Environment and HttpRuntime classes have several properties that contain the name of the website (for example, "mysite"), which is easily accessible. Everything becomes more complicated, if not by default, but, for example, access to an intermediate site slot (which has a website URL such as mysite-staging.azurewebsites.net).

So I'm just wondering if there is a direct way to get this site URL directly. If not, then using one of the mentioned classes to get the site name, and then somehow detect the site slot (which can be set through the configuration value from the Azure portal) will be a solution

+4
source share
1 answer

Edit (2/4/16): You can get URLfrom appSetting / EnvironmentVariable websiteUrl. It will also give you a custom hostname if you have one setting.

There are several ways to do this.

1. From the title HOSTNAME

, <SiteName>.azurewebsites.net. HOSTNAME <SiteName>.azurewebsites.net

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

2. WEBSITE_SITE_NAME Environment Variable

<SiteName>, .azurewebsites.net

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

3. bindingInformation applicationHost.config MWA

, IIS applicationHost.config 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;
}

2

+13

Source: https://habr.com/ru/post/1537428/


All Articles