public static string accessToken = string.Empty;
static void Main(string[] args)
{
try
{
GetTokenWithoutSecretCode();
string url = "https://management.azure.com/subscriptions/SubscriptionID/resourcegroups/ResourceGroupName/providers/Microsoft.Resources/deployments/detdepoyment?api-version=2019-05-01";
string jsonContent = "{ \"properties\": { \"templateLink\": { \"uri\": \"https://storageName.blob.core.windows.net/templates/VMTemplate.json\", \"contentVersion\": \"1.0.0.0\" }, \"parametersLink\": { \"uri\": \"https://storageName.blob.core.windows.net/templates/VMParam.json\", \"contentVersion\": \"1.0.0.0\" }, \"mode\": \"Incremental\" }}";
SpinupVM(url, jsonContent, accessToken);
}
catch (Exception ex)
{
string message = ex.Message;
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
private static void GetTokenWithoutSecretCode()
{
try
{
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").Result;
}
catch
{
throw;
}
}
// POST a JSON string
private static void SpinupVM(string url, string jsonContent, string authToken)
{
JObject json = JObject.Parse(jsonContent);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "PUT";
request.Headers.Add("Authorization", "Bearer " + authToken);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(json.ToString());
request.ContentLength = byteArray.Length;
request.ContentType = "application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch
{
throw;
}
}
要创建此 VM,您必须对此拥有适当的权限。您必须至少添加为该资源组的参与者。