Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Demonstrates how to map a domain name to an Azure website programmatically
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json.Linq;
static class DomainMapper
public static async Task MapDomainName(string domainName)
string clientId = "your-azure-ad-app-client-id"; // create an app in azure ad and obtain these numbers their
string clientSecret = "your-azure-ad-app-client-secret";
string tenantId = "your-tenant-id"; // e.g.
string resourceGroup = "your-resource-group"; // the resource group the website belongs to
string subscriptionId = "your-azure-subscription-id"; // the subscription id the website belongs to
string websiteName ="your-website-name"; // the name of your website
ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
AuthenticationContext context = new AuthenticationContext($"{tenantId}");
AuthenticationResult authenticationResult = await context.AcquireTokenAsync("", clientCredential);
if (authenticationResult == null)
// handle the auth error
string accessToken = authenticationResult?.AccessToken;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
IReadOnlyCollection<string> hostnames = await GetExistingHostnames(subscriptionId, resourceGroup, websiteName, client);
if (!hostnames.Contains(command.DomainName))
string domain = Uri.EscapeUriString(command.DomainName);
string updateUri = $"{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Web/sites/{websiteName}/hostNameBindings/{domain}?api-version=2016-08-01";
HttpResponseMessage response = await client.PutAsync(updateUri, null);
private static async Task<IReadOnlyCollection<string>> GetExistingHostnames(string subscriptionId, string resourceGroup, string websiteName,
HttpClient client)
string getConfigurationUri =
string result = await client.GetStringAsync(getConfigurationUri);
JObject json = JObject.Parse(result);
JArray jsonHostnames = (JArray) (json["properties"]["hostNames"]);
List<string> hostnames = jsonHostnames.Select(x => (string) x).ToList();
return hostnames;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.